将图片从URL上传到Firebase存储

时间:2016-06-07 17:58:50

标签: javascript firebase firebase-storage

我想知道如何通过URL而不是输入(例如)将文件上传到Firebase的存储。我正在从网站上删除图片并检索他们的网址。我想通过foreach语句传递这些URL,并将它们上传到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 file =“http://i.imgur.com/eECefMJ.jpg”;不起作用!

4 个答案:

答案 0 :(得分:4)

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

示例。一旦你从外部网站获得图像网址,这就是你需要的全部内容:

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

答案 1 :(得分:2)

希望这有助于其他人:)

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

答案 2 :(得分:1)

使用fetch命令对此的Javascript解决方案。

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

答案 3 :(得分:0)

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