如何使用 Javascript 将图像副本(位于 URL)保存到 Firebase Storage(网络)?

Emi*_*ily 5 javascript firebase firebase-storage

我正在尝试创建图像的副本(位于网址),并将其保存到 Firebase 的存储设施中。我想存储实际的图像文件而不仅仅是网址。如果我理解正确的话,我首先需要将 url 处的图像转换为 blob 或文件,然后将数据上传到 Firebase 存储。

这是我目前对 Javascript 的尝试:

function savePicture(){
    var url = ["http://carltonvet.com.au/sites/default/files/styles/large/public/images/article/cats.jpg"];
    var blobpic = new Blob(url, {type: 'file'}); 
    console.log(blobpic);

    var user = firebase.auth().currentUser;
        if (user != null) {
            var userid = user.uid; 

            var ref = firebase.storage().ref(userid + "profilePhoto");
            ref.put(blobpic).then(function(snapshot) {
                console.log('Picture is uploaded!');
                console.log(snapshot);

                var filePath = snapshot.metadata.fullPath;
                document.getElementById('picTestAddress').innerHTML = ""+filePath;
                document.getElementById('picTestImage').src = ""+filePath;
        });
        }else{
                console.log("Something went wrong, user is null.");
        }
}
Run Code Online (Sandbox Code Playgroud)

我有两个这样的 HTML 标签:

<div id="picTestAddress"></div>
<img id="picTestImage" />
Run Code Online (Sandbox Code Playgroud)

我很确定这只是保存网址而不是物理图像。

“picTestAddress”被填写为"qAjnfi387DHhd389D9j3r/profilePhoto",并且控制台显示“picTestImage”的以下错误:GET file:///android_asset/www/qAjnfi387DHhd389D9j3r/profilePhoto net::ERR_FILE_NOT_FOUND

我正在使用 Firebase for Web 和 Cordova。我正在我的 Android 手机上测试该应用程序。

我知道该错误是因为它正在我手机的本地文件系统上查找图像。这对我来说很有意义,所以我想我可以通过将应用程序的地址附加到开头来解决这个问题filePath(例如:document.getElementById('picTestImage').src = "https://firebasestorage.googleapis.com/v0/b/MY_APP.appspot.com/o/"+filePath;

为了找到正确的路径,我导航到 Firebase 控制台中的文件位置并复制了“下载 url”地址 - 但是当我检查此内容(通过将其输入到我的网络浏览器中)时,它加载了一个包含一行文本的白色页面,这是原始网址:“ http://carltonvet.com.au/sites/default/files/styles/large/public/images/article/cats.jpg

所以现在我想我只是将 url 保存到存储中,而不是实际的图像文件。

我一直在关注 Firebase 文档,我认为我的上传部分工作正常,但我认为在使用 Javascript 将 url 转换为 blob/文件时失败了。

我查看了其他一些问题,例如:How to store and view images on firebase? 并打算按照这里的示例: https: //github.com/firebase/firepano但它说它现在是一个遗留示例,我似乎无法在 Firebase 的示例部分找到更新版本。

任何有关如何做到这一点的建议或帮助将不胜感激。先感谢您!

Mik*_*ald 4

看起来不错,但我也会考虑一个承诺版本:

function getBlob(url) {
  return new Promise(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function(event){
      var blob = xhr.response;
      resolve(blob);
    };
    xhr.onerror = reject();
    xhr.open('GET', url);
    xhr.send();
  }
}

function storageURLForPhoto(oldURL, newName) {
  getBlob(oldURL)
  .then(function(blob) {
    var picRef = firebase.storage().ref().child(newName);
    return picRef.put(blob)
  })
  .then(function(snapshot) {
    return snapshot.downloadURL;
  });
  .catch(function() {
    // handle any errors
  })
}
Run Code Online (Sandbox Code Playgroud)

更容易推理:)