【问题标题】:How to upload image to firebase cloud storage from input field?如何从输入字段将图像上传到 Firebase 云存储?
【发布时间】:2018-04-09 21:03:28
【问题描述】:

我有一个输入字段,用户可以在其中选择要上传的图像,然后我需要发送到云存储。问题是,我不知道如何获取他们选择的文件。我看到很多问题,如thisthisthis 等。我看到的大多数问题,如this 之一,都是要求在上传之前预览图像。我不认为我需要预览图像,我只想上传它。我该怎么做呢?这是我当前的代码:

function addImage() {
  $("#addImage").append('\
    <input type="file" id="image" accept="image/*">\
    <button type="submit">ok</button>\
    <button onclick="cancelAddImage()">cancel</button>');
  $("#addImage").submit(function() {
    var image = $("#image").files;
    console.log(image);
    storage.ref("images").put(image).then(function(snapshot) {
      console.log('Uploaded a file!');
    });
  });
}

console.log() 给出“未定义”。我还尝试了.files[0] 而不是.files;,还有很多其他的。

【问题讨论】:

    标签: javascript jquery image firebase firebase-storage


    【解决方案1】:

    在您的 html 代码中,您将输入字段与一个 id 放在一起。例如,如果您想从相机上传图片:

    <input type="file" accept="image/*" capture="camera" id="cameraInput">
    

    然后在你的 js 代码中,你会监听这个元素的变化事件:

      let storageRef = firebase.storage().ref('photos/myPictureName')
      let fileUpload = document.getElementById("cameraInput")
    
      fileUpload.addEventListener('change', function(evt) {
          let firstFile = evt.target.files[0] // upload the first file only
          let uploadTask = storageRef.put(firstFile)
      })
    

    当然,您之前需要以某种方式包含 firebase js 库。

    而且如果你写的是老版本的js,还需要把let换成var,加;在你的行尾。

    【讨论】:

      猜你喜欢
      • 2021-10-28
      • 2021-04-21
      • 1970-01-01
      • 2019-08-15
      • 2017-03-27
      • 2021-09-28
      • 1970-01-01
      • 2017-09-25
      相关资源
      最近更新 更多