繁体   English   中英

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

[英]How to save a copy of an image (located at a URL) to Firebase Storage (web) using Javascript?

我正在尝试创建图像的副本(位于 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 用于 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/文件时我失败了。

我浏览了一些其他问题,例如这个问题: 如何在 firebase 上存储和查看图像? 并打算按照这里的示例进行操作: https : //github.com/firebase/firepano但它说它现在是一个遗留示例,我似乎无法在 Firebase 的示例部分找到更新版本。

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

以下工作:

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

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

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

更容易推理:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM