1

I am using the file transfer plugin (org.apache.cordova.file-transfer) v.4.3 to download images from my back-end api.

I am following the conventions specified in the latest realease.
As you can see my destination file is built using cdvfile.

I am using this code:

function fileDownload(serverURL, token, imageName) {

    var deferred = $q.defer();

    var ft = new FileTransfer()

    var fileURL = "cdvfile://localhost/persistent/MyFolder/" + imageName;

    ft.download(encodeURI(serverURL), fileURL,
        function (result) {
            deferred.resolve(result);
        },
        function (reason) {
            deferred.reject(reason);
        },
        false,
        {
            headers: { 'Authorization': 'Bearer ' + token }
        });

    return (deferred.promise);
};

and everything works fine and my files now are save in a custom app folder (MyFolder).

I would like to save the image in my image gallery.

LeftyX
  • 35,328
  • 21
  • 132
  • 193

1 Answers1

0

I am not sure of a way to do this in JavaScript, but I was able to do it in Java for Android and Objective C for iOS. I made a plugin to do this, but I don't know if that is absolutely necessary. All I had to do was pass in the image path after downloading it using fileTransfer:

iOS (Objective C):

self.callbackId = command.callbackId;

//background thread for performance
[self.commandDelegate runInBackground:^{

    NSString* escapedUrl = [[[command arguments] objectAtIndex:0] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *imageURL = [NSURL URLWithString: escapedUrl];

    //background thread for performance
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:imageURL];
    }completionHandler:^(BOOL success, NSError *error) {
        if (success){
            NSLog(@"Image Saved!");
        } else {
            NSLog(@"Error: %@", error);
        }
    }];
}];

Android (Java):

final String path = data.getString(0);
final Activity ctx = this.cordova.getActivity();

try {
    MediaStore.Images.Media.insertImage(ctx.getContentResolver(), path, "" , "");
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

Sorry to answer your question 2 years late. Hopefully this will help someone eventually. I struggled with this for so long and wished someone had answered your question when I first happened upon it

If the method of initially downloading the image above isn't working for anyone, this link did wonders for me: Phonegap - Save image from url into device photo gallery

Community
  • 1
  • 1
Mitch D
  • 79
  • 9