如何在fileReader之后将图像上传到firebase存储

时间:2017-08-09 06:22:55

标签: javascript firebase firebase-storage

我正在尝试将图片上传到必须是blob或文件的firebase存储,我想知道在使用filereader之后我该怎么做?

function image(file, idOfImage){
    var fr = new FileReader();
    var imgCar = document.createElement('img')
    imgCar.id = idOfImage
    fr.onload = function () {
        imgCar.src = fr.result;
    }
    fr.readAsDataURL(file);
    document.body.append(imgCar)
}
// sometime later... I might call uploadImage() if user wants to save this image or other image...
// (I am calling image() a couple of times so multiple images on window)
function uploadImage(idOfImage){
    var image = document.getElementById(idOfImage)
    storage.ref('...').put(image); // I get error since not blob or file
    //storage.ref('...').put(image.src); // I get same error since not blob or file
}

1 个答案:

答案 0 :(得分:0)

好的,首先,您放置在图像功能中的文件是blob 。所以你应该做的就是将它存储在某个地方,或者只使用你放入的任何变量作为文件参数。这样您就可以在uploadImage()中使用它。例如:

// This is for the examples sake, but you need to save the file you give to image() somewhere (e.g. the variable below)
var imageBlob = {};

function image(file, idOfImage) {
  imageBlob = file;
  var fr = new FileReader();
  var imgCar = document.createElement('img');
  imgCar.id = idOfImage;
  fr.onload = function() {
    imgCar.src = fr.result;
  }
  fr.readAsDataURL(file);
  document.body.append(imgCar)
}
// sometime later
function uploadImage() {
  storage.ref('...').put(imageBlob); // I get error since not blob or file
}

如果您使用<input type="file">方法上传,则可以在function uploadImage中执行以下操作:

function uploadImage() {
  // This will get the first uploaded file and upload it to firebase storage
  // All files uploaded are actually blobs (it extends the blob object)
  storage.ref('...').put(input.files[0]);
}
相关问题