【问题标题】:Cordova - download image from URL to the pictures galleryCordova - 从 URL 下载图像到图片库
【发布时间】:2017-07-09 04:20:30
【问题描述】:

我创建了一个简单的 cordova android 应用程序,我试图从 URL 下载图片到图片库,但我真的不知道出了什么问题。 我已经在stackoverflow这里搜索了很多,包括以下链接:

Phonegap - Save image from url into device photo gallery

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

我已经安装了cordova File Transfer插件并尝试从官方网站做示例,但它也不起作用:https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file-transfer/

我尝试了 2 个不同的代码,分别是:

1) 第一次尝试:

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);
        }
    );
}

在此尝试中,我收到警告消息“下载完成:/my_folder/new_file.png”,但我找不到图片的下载位置。 它绝对不在图片库或任何我能找到的地方。

2) 第二次尝试:

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=="
            //}
        }
    );
}

在此尝试中,我收到警告消息“下载完成:file:///data/user/0/com.companyname.xxxxxxx/cache/downloaded-image.png”,但是我也无法在设备中的任何位置找到图片。

我已经在两个不同的安卓设备上试用过这个应用程序。

【问题讨论】:

  • 我建议为这样的东西创建自己的科尔多瓦插件。我有相当多的 android 开发和处理正确创建文件的位置是一个时代的关键词,我不会相信他们的插件。
  • 你可以使用这个功能:stackoverflow.com/a/65314298/1243247它可以工作

标签: javascript android cordova phonegap-plugins cordova-plugins


【解决方案1】:

我就是这样做的。 你需要cordova文件插件 它需要一个网址(在我的情况下为png) 它会将其保存在您的下载文件夹中(使其出现在您手机的图库中)

//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();
}

【讨论】:

  • 感谢您的提示。我赞成你的回答。顺便说一句,我在 iOS 上找不到下载的图像。你能推荐一个适合iOS案例的解决方案吗?
  • 对于 iOS,我推荐这个插件 - github.com/quiply/SaveImage
【解决方案2】:

你应该换行

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

和 如果下载成功,您应该重新扫描您的设备存储,因为 Cordova 不知道文件是否已下载。

所以我做了一个插件,

下载后更新图库的插件。

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

【讨论】:

    【解决方案3】:

    如果您仍在寻找解决方案,请尝试这个适用于 android 的插件

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

    【讨论】:

      【解决方案4】:

      我将此函数与回调一起使用。

      要查看cordovaFileSystem 的不同类型,请参阅here 或通过在控制台中键入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 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()
      }
      

      【讨论】:

        猜你喜欢
        • 2015-06-19
        • 2013-03-12
        • 2016-09-20
        • 1970-01-01
        • 2017-07-20
        • 2018-09-23
        • 2016-03-30
        • 2015-09-15
        • 2021-03-10
        相关资源
        最近更新 更多