将图像从 URL 上传到 Firebase 存储

Upload image from URL to Firebase Storage

我想知道如何通过 URL 而不是输入(例如)将文件上传到 Firebase 的存储中。我正在从网站上抓取图片并检索它们的 URLS。我想通过 foreach 语句传递那些 URLS 并将它们上传到 Firebase 的存储。现在,我有使用此代码的 firebase upload-via-input:

var auth = firebase.auth();
var storageRef = firebase.storage().ref();

function handleFileSelect(evt) {
  evt.stopPropagation();
  evt.preventDefault();
 var file = evt.target.files[0];


  var metadata = {
    'contentType': file.type
  };

  // Push to child path.
  var uploadTask = storageRef.child('images/' + file.name).put(file, metadata);

  // Listen for errors and completion of the upload.
  // [START oncomplete]
  uploadTask.on('state_changed', null, function(error) {
    // [START onfailure]
    console.error('Upload failed:', error);
    // [END onfailure]
  }, function() {
    console.log('Uploaded',uploadTask.snapshot.totalBytes,'bytes.');
    console.log(uploadTask.snapshot.metadata);
    var url = uploadTask.snapshot.metadata.downloadURLs[0];
    console.log('File available at', url);
    // [START_EXCLUDE]
    document.getElementById('linkbox').innerHTML = '<a href="' +  url + '">Click For File</a>';}

请问我要替换什么

var file = evt.target.files[0];

使用外部 URL 而不是手动上传过程?

var 文件 = "http://i.imgur.com/eECefMJ.jpg";不起作用!

如果您只是保存 url 路径,则无需使用 Firebase 存储。 Firebase 存储用于物理文件,而 Firebase 实时数据库可用于结构化数据。

例子。一旦您从外部站点获得图像 url,这就是您所需要的:

var externalImageUrl = 'https://foo.com/images/image.png';

然后您将把它存储在您的 json 结构化数据库中:

databaseReference.child('whatever').set(externalImageUrl);

如果你真的想直接从外部站点下载物理图像到存储,那么这将需要发出 http 请求并接收 blob 响应,或者可能需要服务器端语言..

Javascript 解决方案:How to save a file from a url with javascript

PHP 解决方案:Saving image from PHP URL

希望这对其他人有帮助:)

    // Download a file form a url.
 function saveFile(url) {
 // Get file name from url.
  var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
  var xhr = new XMLHttpRequest();
    xhr.addEventListener("load", transferComplete);
xhr.addEventListener("error", transferFailed);
xhr.addEventListener("abort", transferCanceled);

  xhr.responseType = 'blob';
  xhr.onload = function() {
    var a = document.createElement('a');
    a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
    a.download = filename; // Set the file name.
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    delete a;

          if (this.status === 200) {
        // `blob` response
        console.log(this.response);
        var reader = new FileReader();
        reader.onload = function(e) {

                    var auth = firebase.auth();
    var storageRef = firebase.storage().ref();

                     var metadata = {
        'contentType': 'image/jpeg'
      };

                    var file = e.target.result;
                    var base64result = reader.result.split(',')[1];
                    var blob = b64toBlob(base64result);


                       console.log(blob);

                var uploadTask = storageRef.child('images/' + filename).put(blob, metadata);

                uploadTask.on('state_changed', null, function(error) {
        // [START onfailure]
        console.error('Upload failed:', error);
        // [END onfailure]
      }, function() {
        console.log('Uploaded',uploadTask.snapshot.totalBytes,'bytes.');
        console.log(uploadTask.snapshot.metadata);
        var download = uploadTask.snapshot.metadata.downloadURLs[0];
        console.log('File available at', download);
        // [START_EXCLUDE]
        document.getElementById('linkbox').innerHTML = '<a href="' +  download + '">Click For File</a>';
        // [END_EXCLUDE]
      });
            // `data-uri`

        };
        reader.readAsDataURL(this.response);        
    };
  };



  xhr.open('GET', url);
  xhr.send();
}

function b64toBlob(b64Data, contentType, sliceSize) {
  contentType = contentType || '';
  sliceSize = sliceSize || 512;

  var byteCharacters = atob(b64Data);
  var byteArrays = [];

  for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    var slice = byteCharacters.slice(offset, offset + sliceSize);

    var byteNumbers = new Array(slice.length);
    for (var i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    var byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  var blob = new Blob(byteArrays, {type: contentType});
  return blob;
}



    function transferComplete(evt) {        


            window.onload = function() {
      // Sign the user in anonymously since accessing Storage requires the user to be authorized.
    auth.signInAnonymously().then(function(user) {
        console.log('Anonymous Sign In Success', user);
        document.getElementById('file').disabled = false;
      }).catch(function(error) {
        console.error('Anonymous Sign In Error', error);
      });
    } 
}



function transferFailed(evt) {
  console.log("An error occurred while transferring the file.");
}

function transferCanceled(evt) {
  console.log("The transfer has been canceled by the user.");
}

This answer 类似于@HalesEnchanted 的答案,但代码更少。在这种情况下,它是通过 Cloud Function 完成的,但我认为同样可以从前端完成。还要注意 createWriteStream() 如何有一个类似于 bucket.upload().

的选项参数
const fetch = require("node-fetch");

const bucket = admin.storage().bucket('my-bucket');
const file = bucket.file('path/to/image.jpg');

fetch('https://example.com/image.jpg').then((res: any) => {
  const contentType = res.headers.get('content-type');
  const writeStream = file.createWriteStream({
    metadata: {
      contentType,
      metadata: {
        myValue: 123
      }
    }
  });
  res.body.pipe(writeStream);
});

Javascript 使用 fetch 命令解决这个问题。

var remoteimageurl = "https://example.com/images/photo.jpg"
var filename = "images/photo.jpg"

fetch(remoteimageurl).then(res => {
  return res.blob();
}).then(blob => {
    //uploading blob to firebase storage
  firebase.storage().ref().child(filename).put(blob).then(function(snapshot) {
    return snapshot.ref.getDownloadURL()
 }).then(url => {
   console.log("Firebase storage image uploaded : ", url); 
  }) 
}).catch(error => {
  console.error(error);
});