I have been using phonegap and am trying to download wallpaper jpgs to the device camera roll. I have been testing this on the mobile phonegap app connecting to phonegap server. The code I am using goes as follows:
function DownloadFile(URL, Folder_Name, File_Name) {
if (URL == null && Folder_Name == null && File_Name == null) {
return;
}
else {
download(URL, Folder_Name, File_Name); //If available download function
}
}
function download(URL, Folder_Name, File_Name) {
//step to request a file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, fileSystemFail);
function fileSystemSuccess(fileSystem) {
var download_link = encodeURI(URL);
ext = download_link.substr(download_link.lastIndexOf('.') + 1); //Get extension of URL
var directoryEntry = fileSystem.root; // to get root path of directory
directoryEntry.getDirectory(Folder_Name, { create: true, exclusive: false }, onDirectorySuccess, onDirectoryFail); // creating folder in sdcard
var rootdir = fileSystem.root;
var fp = rootdir.toURL(); // Returns Fulpath of local directory
fp = fp + Folder_Name +"/"+ File_Name + ".jpg"; // fullpath and name of the file which we want to give
filetransfer(download_link, fp);
}
function onDirectorySuccess(parent) {
// Directory created successfuly
}
function onDirectoryFail(error) {
//Error while creating directory
alert("Unable to create new directory: " + error.code);
}
function fileSystemFail(evt) {
//Unable to access file system
alert(evt.target.error.code);
}
}
function filetransfer(download_link, fp) {
var fileTransfer = new FileTransfer();
// File download function with URL and local path
fileTransfer.download(download_link, fp,
function (entry) {
console.log("cdvfile://localhost/persistent/" + fp);
alert("download complete: " + entry.fullPath.slice(1));
},
function (error) {
//Download abort errors or download failed errors
alert("download error source " + error.source);
alert("download error target " + error.target);
//alert("upload error code" + error.code);
}
);
}
What is interesting is that when I click my button that fires these methods I receive an alert saying download complete: file_name. However, there never appears an image in my camera roll. Is this an iOS issue? I've tried looking at this natively as opposed to simulating it with phonegap serve and it makes no difference.
I've also tried a file_path like so "cdvfile://localhost/persistent/"+Folder_name+"/"+ File_name+"."+ext;
with no different results.
In a difference post http://community.phonegap.com/nitobi/topics/file_download_not_working_properly_on_ios the answer for iOS was to use
<access origin="*" />
I made sure to use that in my config.xml file.
Does anyone have an idea as to what I am missing? This code has worked for others and oddly it states it completes correctly.
Related
I am trying to add offline functionality to my HTML5 video player. I am attempting to write the files into the chrome file system as a blob and then read them from there. I believe that I am running into an issue where the files are not actually being written, just the file name. As my below code is currently constituted, it works, though still only if it is permanently connected to the internet. My goal is to have the files download to a persistent directory in the filesystem and then continue to play if the internet is disconnected.
$(document).ready(function() {
var dir = "http://www.kevmoe.com/networks/gsplayer/";
var fileextension = ".mp4";
var srcfiles = $.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: dir,
success: function(data) {
//List all .mp4 file names in the page
$(data).find("a:contains(" + fileextension + ")").each(function() {
var filename = $(this).attr("href").replace(window.location.host, "").replace("http://", "");
$("#container").append("<div id='div1' class='video'><video id='video1' class='vidarray' preload='none' poster='bkg.png'><source src='" + filename + "' type='video/mp4'></video></div>");
async: false;
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTANT, 200000 * 1024 * 1024, initFS, errorHandler);
function initFS(fs) {
console.log('filesystem engaged'); // Just to check if everything is OK :)
// place the functions you will learn bellow here
function errorHandler(err) {
var msg = 'An error occured: ';
};
function createDir(rootDir, folders) {
rootDir.getDirectory(folders[0], {
create: true
}, function(dirEntry) {
if (folders.length) {
createDir(dirEntry, folders.slice(1));
}
}, errorHandler);
};
createDir(fs.root, 'files/video/'.split('/'));
fs.root.getDirectory('video', {}, function(dirEntry) {
var dirReader = dirEntry.createReader();
dirReader.readEntries(function(entries) {
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
if (entry.isDirectory) {
console.log('Directory: ' + entry.fullPath);
} else if (entry.isFile) {
console.log('File: ' + entry.fullPath);
}
}
}, errorHandler);
}, errorHandler);
fs.root.getFile(filename, {
create: true,
exclusive: true
}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
var blob = new Blob([data], {
type: 'video/mp4'
});
fileWriter.write(blob);
}, errorHandler);
console.log('file downloaded');
}, errorHandler);
//Try to add an event listener for when all files are finished loading into file system. Then use another function to source the videos locally.
var dirReader = fs.root.createReader();
var entries = [];
// Call the reader.readEntries() until no more results are returned.
dirReader.readEntries(function(results) {
//List all .mp4 file names in the page
$(results).find("a:contains(" + fileextension + ")").each(function() {
var filename = $(this).attr("href").replace(window.location.host, "").replace("http://", "");
$("#container").append("<div id='div1' class='video'><video id='video1' class='vidarray' preload='none' poster='bkg.png'><source src='" + filename + "' type='video/mp4'></video></div>");
async: false;
}, errorHandler);
});
};
function errorHandler() {
console.log('An error occured');
};
});
var videos = $('.video');
//handle ending of video
videos.find('video').on('ended', function() {
playNextVideo(videos);
});
// start with the first one
playNextVideo(videos);
function playNextVideo(videoList) {
var activeVideo = videoList.filter('.active').removeClass('active'), // identify active video and remove active class
activeIndex = videoList.index(activeVideo), // get the active video index in the group
nextVideo = videoList.eq(activeIndex + 1), // get the next video in line
actualVideo;
// if there is no next video start from first
if (nextVideo.length == 0) nextVideo = videoList.first();
// pause all videos
videoList.find('video').each(function() {
this.pause();
})
// get reference to next video element
actualVideo = nextVideo.find('video').get(0);
// add active class to next video
nextVideo.addClass('active');
// load and play
actualVideo.volume = 0.04;
actualVideo.load();
actualVideo.play();
}
}
});
});
filesystem: protocol stores files with reference to same origin as document which requests LocalFileSystem. That is, if JavaScript at Question is created at, for example, http://example.org, the path to LocalFileSystem should be same origin as http://example.org, not file: protocol.
If you are trying to store files or folders for accessing at file: protocol, offline, you can create an .html document to use as a template bookmark.
Visit the local .html file once while online to get files and populate LocalFileSystem. If navigator.onLine is true, navigate to http://example.org, else get and process files and folders stored at LocalFileSystem.
Create a list as JSON or JavaScript Array to store list of files to fetch, instead of parsing an .html document for file locations.
Store local file as a bookmark. Launch Chromium, Chrome with --allow-file-access-from-files flag set to access filesystem: protocol from file: protocol and file: protocol at filesystem: protocol, if not online.
<!DOCTYPE html>
<html>
<head>
<title>LocalFileSystem Offline Videos Bookmark</title>
</head>
<body>
<script>
// location to visit if online
const onLineURL = "https://lorempixel.com/"
+ window.innerWidth
+ "/"
+ window.innerHeight + "/cats";
const props = {
requestedBytes: 1024 * 1024 * 20000,
folder: "videos",
// list of files to fetch for offline viewing
mediaList: [
"http://mirrors.creativecommons.org/movingimages/webm/"
+ "ScienceCommonsJesseDylan_240p.webm"
, "https://nickdesaulniers.github.io/netfix/demo/frag_bunny.mp4"
]
};
let grantedBytes = 0;
function getLocalFileSystem ({requestedBytes = 0, mediaList=[], folder = ""}) {
if (!requestedBytes || !mediaList.length || !folder) {
throw new Error("requestedBytes: Number"
+ " or mediaList: Array"
+ " or folder: String not defined");
};
// do stuff with `filesystem:` URL
function processLocalFilePath(localPath) {
const video = document.createElement("video");
document.body.appendChild(video);
video.controls = true;
video.src = localPath;
}
function errorHandler(err) {
console.log(err);
}
function writeFile(dir, fn, fp, localPath) {
console.log(dir, fn, fp, localPath);
dir.getFile(fn, {}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
// do stuff when file is written
console.log(e.type, localPath + " written");
window.webkitResolveLocalFileSystemURL(localPath
, function(file) {
// file exists in LocalFileSystem
processLocalFilePath(localPath);
}, errorHandler)
};
fileWriter.onerror = errorHandler;
fetch(fp).then(function(response) {
return response.blob()
}).then(function(blob) {
fileWriter.write(blob);
}).catch(errorHandler)
}, errorHandler);
}, errorHandler);
}
if (mediaList && mediaList.length) {
navigator.webkitTemporaryStorage.requestQuota(requestedBytes
, function(grantedBytes_) {
grantedBytes = grantedBytes_;
console.log("Requested bytes:", requestedBytes
, "Granted bytes:", grantedBytes);
window.webkitRequestFileSystem(window.TEMPORARY
, grantedBytes
, function(fs) {
const url = fs.root.toURL();
mediaList.forEach(function(filename) {
const localPath = url + folder + "/"
+ filename.split("/").pop();
window.webkitResolveLocalFileSystemURL(localPath
, function(file) {
// file exists in LocalFileSystem
console.log(localPath + " exists at LocalFileSystem");
processLocalFilePath(localPath)
}, function(err) {
console.log(err, localPath
+ " not found in LocalFileSystem");
// Exception is thrown if file
// or folder path not found
// create `folder` directory, get files
fs.root.getDirectory(folder, {}
, function(dir) {
writeFile(dir
, filename.split("/").pop()
, filename
, localPath);
}),
errorHandler
})
})
})
}, errorHandler)
}
}
if (location.href !== onLineURL && navigator.onLine) {
location.href = onLineURL;
} else {
getLocalFileSystem(props);
}
</script>
</body>
</html>
See also
How to use webkitRequestFileSystem at file: protocol
How to print all the txt files inside a folder using java script
Read local XML with JS
How to Write in file (user directory) using JavaScript?
An alternative approach could be to utilize ServiceWorker
Adding a Service Worker and Offline into your Web App
Service Worker Sample: Custom Offline Page Sample
Your user must grant your app permission to store data locally before your app can use persistent storage.
That's why you have to request quota first. The amount of bytes you ask for is 200000 * 1024 * 1024 bytes.
window.storageInfo.requestQuota(PERSISTENT, 200000 * 1024 * 1024,
function(grantedBytes) {
window.requestFileSystem(window.PERSISTENT, grantedBytes, onInitFs, errorHandler);
},
errorHandler
);
MDN documentation
I noticed you are writing this for Chrome, here's how you manage the quota in Chrome
I'm building an app with PhoneGap Build, only targeting Android. One of the features is to download a file from a web server to the device.
This code works perfectly on Android 4.x, but doesn't work on Android 5.x and above:
var URL = 'https://example.com/path/to/file.pdf?auth_token=123xxxx';
var Folder_Name = 'Download';
var File_Name = URL.split('/');
File_Name = File_Name[File_Name.length - 1].split('?');
File_Name = File_Name[0];
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, fileSystemFail);
function fileSystemSuccess(fileSystem) {
var download_link = encodeURI(URL);
var directoryEntry = fileSystem.root; // to get root path of directory
directoryEntry.getDirectory(Folder_Name, {
create: true,
exclusive: false
}, onDirectorySuccess, onDirectoryFail); // creating folder in sdcard
var rootdir = fileSystem.root;
var fp = rootdir.toURL(); // Returns Fullpath of local directory
fp = fp + "/" + Folder_Name + "/" + File_Name; // fullpath and name of the file which we want to give
console.log("Path to local file: " + fp);
// download function call
filetransfer(download_link, fp);
}
function onDirectorySuccess(parent) {
console.log('directory created successfully');
// Directory created successfuly
}
function onDirectoryFail(error) {
//Error while creating directory
console.log("Unable to create new directory: " + error.code);
}
function fileSystemFail(evt) {
//Unable to access file system
console.log(evt.target.error.code);
}
function filetransfer(download_link, fp) {
var fileTransfer = new FileTransfer();
// File download function with URL and local path
fileTransfer.download(download_link, fp,
function(entry) {
alert('The file was successfully downloaded, you can access it in /' + Folder_Name + '/' + File_Name + '.');
console.log("download complete: " + entry.fullPath);
},
function(error) {
//Download abort errors or download failed errors
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("download error code" + error.code);
}
);
}
Don't get anything in the console, no error and none of the log lines, meaning that none of the callbacks gets triggered.
Did anybody else have this mysterious issue?
Thanks
try to install these versions.
phonegap plugin remove cordova-plugin-file
phonegap plugin remove cordova-plugin-file-transfer
phonegap plugin add cordova-plugin-file#4.3.3
phonegap plugin add cordova-plugin-file-transfer#1.5.1
I am use these versions and i havent problems in Anrdoid 5, 6, 7. Try it.
I have more than 2 weeks that i tried to download file PDF in phonegap application using the File Transfer Plugin but it didn't work!! i make everything for that:
-installing the last version of phonegap
-installing the last version of File Transfer plugin
And this is the code to integrate in Javascript interface:
var fileTransfer = new FileTransfer();
fileTransfer.download(
"http://developer.android.com/assets/images/home/ics-android.png",
"file://sdcard/ics-android.png",
function(entry) {
alert("download complete: " + entry.fullPath);
},
function(error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
});
But it seems wrong!!! I have like a result last three alerts in an android device:
-Download error source
-Download error target
-Upload error code
What i should doing?!!
Request you to check out my github page that contains a sample Cordova app which downloads PDF file from external URL and downloads it to the device.
This sample app is tested both in iOS and android devices. Hope it helps.
According to file transfer plugin documentation, first of all you need to create a file where you will store your remote data. Your code should look like this:
{
//call this after onDeviceReady event
...
var savePath = cordova.file.externalRootDirectory;
var fileName = "ics-android.png";
var url = encodeURI("http://developer.android.com/assets/images/home/ics-android.png");
downloadFile(savePath, fileName, url);
...
}
function downloadFile(savePath, fileName, remoteURL) {
window.resolveLocalFileSystemURL(savePath, function (dirEntry) {
console.log('file system open: ' + dirEntry.name);
createFile(dirEntry, fileName, function (fileEntry) {
download(remoteURL, fileEntry);
});
}, function (err) { alert(err) });
}
function createFile(dirEntry, fileName, callback) {
// Creates a new file or returns the file if it already exists.
dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {
callback(fileEntry);
}, function (err) { alert(err) });
}
function download(remoteURL, fileEntry) {
var fileURL = fileEntry.toURL();
var fileTransfer = new FileTransfer();
fileTransfer.download(
remoteURL,
fileURL,
function (entry) {
alert("download complete: " + entry.fullPath);
},
function (error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
});
}
Note that for path I use cordova.file.externalRootDirectory, so you get root sdcard path for file.
I'm using Cordova to make android and iOS app, now I would like to check if file already exist in the dirctory.
First I download file from server and save it locally using the code below
$scope.downloadFile = function(){
alert(cordova.file.dataDirectory)
var fileTransfer = new FileTransfer();
var uri = encodeURI("http://example.com/files/th/001.mp3");
var downloadPath = cordova.file.dataDirectory+'001.mp3'; // ANDROID
fileTransfer.download(
uri,
downloadPath,
function(entry) {
$scope.savepath = entry.toInternalURL();
alert("download complete: " + entry.toURL());
alert('saved at : '+entry.toInternalURL());
},
function(error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
},
false,
{
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
}//End DownloadFile
and I would like to check if the file already exist using checkIfFileExists(path) method
function checkIfFileExists(path){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
//alert('result: '+JSON.stringify(fileSystem.root))
fileSystem.root.getFile(path, { create: false }, fileExists, fileDoesNotExist);
}, getFSFail); //of requestFileSystem
}
function fileExists(fileEntry){
alert("File " + fileEntry.fullPath + " exists!");
}
function fileDoesNotExist(){
alert("file does not exist");
}
function getFSFail(evt) {
console.log(evt.target.error.code);
}
I checked on my phone, the file is already saved to Android/data/com.myname.myappname/file/001.mp3
but the problem is the code always show file does not exist whenever I use the path like
cordova.file.dataDirectory+'001.mp3';
or cdvfile://localhost/persistent/files/001.mp3
or 'cdvfile://localhost/files/001.mp3'
so I would like to ask that the real path that I need to use to check if the file exist or not.
Please provide me any suggestion.
Regards.
Do you need to use or CheckFileExists? You could try using Phonegap's FileReader method?
var reader = new FileReader();
var fileSource = cordova.file.dataDirectory+'001.mp3'
reader.onloadend = function(evt) {
if(evt.target.result == null) {
// Null? You still have a problem: file doesn't exist.
} else {
// Otherwise the file exists.
}
};
//Check if the file exists
reader.readAsDataURL(fileSource);
I've already managed to save a web page (x/html) successfully, but I'd also like to save the images and mp4 videos that are contained in it, for further visualization in offline mode.
I've got access to the iOS filesystem, so I save the html by obtaining the code through an AJAX request, and later saving it to a file.
I don't really know how to do the same with video and images. I have a server to which I can send queries from my app, so it shows exclusively the content I need to download, with the optimal headers in case its necessary. I just don't know how to "download" it from the client side (Javascript).
Thanks in advance for any help.
You can use a FileTransfer object to download a remote image to a local file.
This is the latest official sample snippet:
// !! Assumes filePath is a valid path on the device
var fileTransfer = new FileTransfer();
var uri = encodeURI("http://some.server.com/download.php");
fileTransfer.download(
uri,
filePath,
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
false,
{
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
You can only do it natively I'm afraid.
I'm doing it through a FileDownload PhoneGap Plugin that I wrote, using NSURLConnection. I pass in the url to download to the plugin through Javascript, and a target location (and it even gives me download progress).
Have not tested it yet, but the documentation at PhoneGap looks quite promising http://docs.phonegap.com/en/1.0.0/phonegap_file_file.md.html
I have used this snippet on my ios app project:
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, success, fail);
var target_directory="";
function fail() {
//alert("failed to get filesystem");
}
function downloadImage(url, filename){
alert("download just started.");
try{
var ft = new FileTransfer();
ft.download(
url,
target_directory + filename,
function(entry) {
//alert("download complete!:" + entry.nativeURL ); //path of the downloaded file
},
function(error) {
//alert("download error" + error.code);
//alert("download error" + JSON.stringify(error));
}
);
}
catch (e){
//alert(JSON.stringify(e));
}
}
function success(fileSystem) {
target_directory = fileSystem.root.nativeURL; //root path
downloadImage(encodeURI("http://upload.wikimedia.org/wikipedia/commons/2/22/Turkish_Van_Cat.jpg"), "cat.jpg"); // I just used a sample url and filename
}