Cordova - download image from URL to the pictures gallery

偶尔善良 提交于 2021-01-01 06:31:31

问题


I created a simple cordova android app and I am trying to download an image from an URL to the pictures gallery, but I really can't figure out what is going wrong. I have already searched a lot here in stackoverflow, including the following links:

Phonegap - Save image from url into device photo gallery

How to save an Image object into a file in Android with Phonegap?

I have installed cordova File Transfer plugin and tried to do the example from the official site, but it didn't work too: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file-transfer/

I tried 2 different codes, which are:

1) First attempt:

document.getElementById("myBtn").addEventListener("click", function () {
    download("http://cordova.apache.org/static/img/cordova_bot.png", "data", "new_file");
});

function download(URL, Folder_Name, File_Name) {
    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();
        fp = fp + "/" + Folder_Name + "/" + File_Name + "." + ext; // fullpath and name of the file which we want to give
        filetransfer(download_link, fp);
    }

    function onDirectorySuccess(parent) {
        // Directory created successfuly
    }

    function onDirectoryFail(error) {
        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();
    fileTransfer.download(download_link, fp,
        function (entry) {
            alert("download complete: " + entry.fullPath);
            //cordova.plugins.imagesaver.saveImageToGallery(entry.fullPath, successCallback, errorCallback);
        },
        function (error) {
            alert("download error source " + error.source);
        }
    );
}

In this attempt, I get the alert message "download complete: /my_folder/new_file.png" but I can't find where the picture is downloaded. It is definitely not in the pictures gallery or anywhere I can find it.

2) Second attempt:

function download() {
    window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {

        var url = 'http://cordova.apache.org/static/img/cordova_bot.png';
        fs.root.getFile('downloaded-image.png', {
            create: true,
            exclusive: false
        }, function (fileEntry) {
            file_transfer(fileEntry, encodeURI(url), true);

        }, onErrorCreateFile);

    }, onErrorLoadFs);
}

function onErrorLoadFs(msg){
    alert(msg);
}

function onErrorCreateFile(msg){
    alert(msg);
}

function file_transfer(fileEntry, uri, readBinaryData) {

    var fileTransfer = new FileTransfer();
    var fileURL = fileEntry.toURL();

    fileTransfer.download(
        uri,
        fileURL,
        function (entry) {
            alert("download complete: " + entry.toURL());

            if (readBinaryData) {
                // Read the file...
                readBinaryFile(entry);
            } else {
                // Or just display it.
                displayImageByFileURL(entry);
            }

        },
        function (error) {
            alert("download error source " + error.source);
            alert("download error target " + error.target);
            alert("upload error code" + error.code);
        },
        null, // or, pass false
        {
            //headers: {
            //    "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
            //}
        }
    );
}

In this attempt, I get the alert message "download complete: file:///data/user/0/com.companyname.xxxxxxx/cache/downloaded-image.png", but I also can't find the picture anywhere in the device.

I have already tried the application in two different android devices.


回答1:


This is how I did it. you will need the cordova file plugin it wil take a url(png in my case) and it will save it in your download folder (which makes it apear in the gallery of your phone)

//download file to device
function DownloadToDevice(fileurl) {
  var blob = null;
  var xhr = new XMLHttpRequest();
  xhr.open("GET", fileurl);
  xhr.responseType = "blob";//force the HTTP response, response-type header to be blob
  xhr.onload = function()
  {
      blob = xhr.response;//xhr.response is now a blob object
      console.log(blob);
      var storageLocation = "";
     switch (device.platform) {
         case "Android":
             storageLocation = 'file:///storage/emulated/0/';
             break;
         case "iOS":
             storageLocation = cordova.file.documentsDirectory;
             break;
     }
     var folderpath = storageLocation + "Download";
     var filename = "Myimg.png";
     var DataBlob = blob;
      window.resolveLocalFileSystemURL(folderpath, function(dir) {
        dir.getFile(filename, {create:true}, function(file) {
                file.createWriter(function(fileWriter) {
                    fileWriter.write(DataBlob);
                    //Download was succesfull
                }, function(err){
                  // failed
                  console.log(err);
                });
        });
      });
  }
  xhr.send();
}



回答2:


You should change the line

window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, 
->
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, 

and if download success, you should re-scan your device storage, because Cordova does not know if the file is downloaded.

so i made a plugin ,

It is a plugin that updates the gallery after downloading.

https://github.com/pouu69/cordova-plugin-gallery-refresh




回答3:


If you are still looking for solution try this working plugin for android

cordova plugin add cordova-plugin-downloadimage-to-gallery



回答4:


I use this function with callbacks.

To check the different types of cordovaFileSystem see here or check the ones available to you by typing in the console console.log(cordova.file)

downloadFileToDevice('https://example.com/image.jpg', 'myimg.jpg', cordova.file.cacheDirectory,
 (err, filePath) => {
    if (err) {
      console.log('An error was found: ', err)
    } else {
      console.log('file downloaded successfully to: ' + filePath)
    }
  })

Function declaration

function downloadFileToDevice (fileurl, filename, cordovaFileSystem, callback) {
  var blob = null
  var xhr = new XMLHttpRequest()
  xhr.open('GET', fileurl)
  xhr.responseType = 'blob' // force the HTTP response, response-type header to be blob
  xhr.onload = function () {
    blob = xhr.response // xhr.response is now a blob object
    var DataBlob = blob
    window.resolveLocalFileSystemURL(cordovaFileSystem, function (dir) {
      dir.getFile(filename, { create: true }, function (file) {
        file.createWriter(function (fileWriter) {
          fileWriter.write(DataBlob)
          callback(null, cordovaFileSystem + filename)
        }, function (err) {
          callback(err)
        })
      })
    })
  }
  xhr.send()
}


来源:https://stackoverflow.com/questions/42335220/cordova-download-image-from-url-to-the-pictures-gallery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!