【问题标题】:How to save a copy of an image (located at a URL) to Firebase Storage (web) using Javascript?如何使用 Javascript 将图像的副本(位于 URL)保存到 Firebase 存储(网络)?
【发布时间】:2017-05-07 01:37:39
【问题描述】:

我正在尝试创建图像的副本(位于 url),并将其保存到 Firebase 的存储设施。我想存储实际的图像文件而不仅仅是 url。如果我理解正确,我首先需要将 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.");
        }
}

我有两个这样的 HTML 标签:

<div id="picTestAddress"></div>
<img id="picTestImage" />

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

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

我正在使用 Firebase for Web 和 Cordova。我正在我的安卓手机上测试这个应用程序。

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

为了找到正确的路径,我在 Firebase 控制台中导航到文件的位置并复制了“下载 url”地址 - 但是当我检查这个(通过将其输入到我的网络浏览器中)时,它加载了一个包含一个的白页文本行,即原始 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 示例部分中的更新版本。

任何有关如何执行此操作的建议或帮助将不胜感激。 先感谢您!

【问题讨论】:

  • 我猜第一个问题是:为什么?您可以将另一个 URL 存储在实时数据库中,然后轻松将其下载到您的应用程序中(请参阅零到应用程序:youtube.com/watch?v=xAsvwy1-oxE)。否则,您需要 XHR 下载文件,然后重新上传,如下所示:firebase.google.com/docs/storage/web/…
  • 嗨,迈克,感谢您的评论,我想存储图像而不是 url,以防托管图像的第三方更改或删除它,这反过来会破坏我应用程序上的链接.您发布的链接帮助我使其正常工作,我将在下面发布解决方案。再次感谢!

标签: javascript firebase firebase-storage


【解决方案1】:

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

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

更容易推理:)

【讨论】:

    【解决方案2】:

    以下作品:

    function savePhoto(){
    
        var url = "http://www.planetware.com/photos-large/F/france-paris-eiffel-tower.jpg";
        // First, download the file:
        var xhr = new XMLHttpRequest();
        xhr.responseType = 'blob';
        xhr.onload = function(event) {
        var blob = xhr.response;
    
        // Get the current user:            
        var user = firebase.auth().currentUser;
        if (user != null) {
        var userid = user.uid; 
    
        // Define where to store the picture:
        var picRef = firebase.storage().ref(userid + "/profilePhoto");
    
        // Store the picture:
        picRef.put(blob).then(function(snapshot) {
        console.log('Picture uploaded!');
    
        // Now get image from storage and display in div...
        picRef.getDownloadURL().then(function(pic) {
            var userspic = pic;
            document.getElementById('picTestImage').src = userspic;
    
        }).catch(function(error) {
            console.log("There was an error: "+error);
        });
    
        });
        }else{
            console.log("We weren't able to confirm there is a current user, something went wrong.");
        }
    
      };
      xhr.open('GET', url);
      xhr.send();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-14
      • 2020-12-18
      • 2017-08-10
      • 2019-03-10
      • 1970-01-01
      • 2021-10-14
      • 2021-04-07
      • 2021-03-29
      相关资源
      最近更新 更多