Phonegap - Save image from url into device photo gallery
This is file download code which can be used by anyone. You just have three parameters to use this like-
1) URL
2) Folder name which you want to create in your Sdcard
3) File name (You can give any name to file)
All types of file can download by using this code. you can use this as .js
And this works on IOS
also.
//First step check parameters mismatch and checking network connection if available call download function
function DownloadFile(URL, Folder_Name, File_Name) {
//Parameters mismatch check
if (URL == null && Folder_Name == null && File_Name == null) {
return;
}
else {
//checking Internet connection availablity
var networkState = navigator.connection.type;
if (networkState == Connection.NONE) {
return;
} else {
download(URL, Folder_Name, File_Name); //If available download function call
}
}
}
//Second step to get Write permission and Folder Creation
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.fullPath; // Returns Fulpath of local directory
fp = fp + "/" + Folder_Name + "/" + File_Name + "." + ext; // fullpath and name of the file which we want to give
// download function call
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);
}
}
//Third step for download a file into created folder
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("download complete: " + entry.fullPath);
},
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);
}
);
}
Useful Link
Cordova - Save image from url into device photo gallery
The images were being saved, but needed the Media Scanner to index the images on gallery
Media Scanner:
MediaScannerConnection provides a way for applications to pass a newly
created or downloaded media file to the media scanner service. The
media scanner service will read metadata from the file and add the
file to the media content provider.
How was working with Apache Cordova / PhoneGap it provides no native method to refresh the images in the native gallery, I had to just look for a plugin to do this job. The plugins I found were:
cordova-mediascanner-plugin
MediaScannerPlugin
Both have a basic documentation, however i used cordova-mediascanner-plugin.
By implementing this plugin, just modified my filetransfer
method
function filetransfer(download_link, fp) {
var fileTransfer = new FileTransfer();
console.log(fp);
// File download function with URL and local path
fileTransfer.download(download_link, fp,
function (entry) {
//alert("download complete: " + entry.fullPath);
window.plugins.scanmedia.scanFile(fp, function (msg) {
alert("Success ScanMedia");
}, function (err) {
alert("Fail ScanMedia: " + err);
})
},
function (error) {
//Download abort errors or download failed errors
console.log(error);
alert(error.exception);
alert("download error source " + error.source);
//alert("download error target " + error.target);
//alert("upload error code" + error.code);
}
);
}
phonegap download and save images from a url to the application installation folder
You can use a phonegap plugin.
Look at http://plugins.cordova.io/#/package/de.fastr.phonegap.plugins.downloader
It downloads multiple files to persistant storage on android and ios.
How to download picture with Phonegap Filetransfer to image gallery in iOS
I would mark this as a duplicate of Phonegap - Save image from url into device photo gallery
I was happy with the answer by M165437 and my comments. That answered my question.
Phonegap: How to save a HTML5 canvas as image to device photo gallery/library
I don't think you can make the image save in the gallery using just JavaScript but you can send the user to the image or display the image where the user can manually save it.
Phonegap Build: download image in one of the folders of your app
As far as I learned you cannot write to your own app (change items inside your app - /www folder on Android).
My solution was to save images to PERSISTENT storage (sdcard usually).
You can get the path of your app's persistent storage with these steps:
function onDeviceReady() {
console.log('Device Platform: ' + device.platform); // returns 'Android' or 'iOS' for instance
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
cacheFolderSubPath = "Android/data/com.id.myApp/cache/"; // this is app's cache folder that is removed when you delete your app! (I don't know what this path should be for iOS devices)
}
Then inside gotFS success callback
function gotFS(fileSystem) {
var nturl = fileSystem.root.toNativeURL(); // cdvfile://localhost/persistent/
window.resolveLocalFileSystemURL(nturl+cacheFolderSubPath, onResolveSuccess, onResolveFail);
}
and in onResolveSuccess
function onResolveSuccess(fileEntry){
appCachePath = fileEntry.toNativeURL()+"/"; // file:///storage/sdcard0/Android/data/com.id.myApp/cache/ in my case but some other Androids have storage/emulated/0 or something like that ...
continueCustomExecution();
}
and now in continueCustomExecution() you can run your program and do whatever it is you do ... and in this case download images into appCachePath that we got earlier. You can now successfully reference images in src tags with our appCachePath+yourImageName.
Unfortunately I still don't know how to download an image successfully on iOS. I get an error code 1 with FileTransfer plugin ... (saving to file:///var/mobile/Applications/my.app.id/Documents/). Probably should save somewhere else but this is the path I get when requesting PERSISTENT FileSystem.
Cheers
Related Topics
Jquery Animate() and Backgroundcolor
Repeat Animation Every 3 Seconds
Html5 Video - Percentage Loaded
How to Determine If ::Before Is Applied to an Element
Performance of CSS Transitions VS. Js Animation Packages
Disable Elastic Scrolling in Safari
Bootstrap Modal: Background Jumps to Top on Toggle
Get Element's Custom CSS Properties (-Mystyle) Using JavaScript
Jquery: How to Check If the Element Has Certain CSS Class/Style
Count Animation from Number a to B
Webkit-Transform Overwrites Z-Index Ordering in Chrome 13
Override Styles in a Shadow-Root Element
How to Post Urlencoded Form Data With $Http Without Jquery