簡體   English   中英

如何從輸入字段將圖像上傳到Firebase雲存儲?

[英]How to upload image to firebase cloud storage from input field?

我有一個輸入字段,用戶可以在其中選擇要上傳的圖像,然后將其發送到雲存儲。 問題是,我不知道如何獲取他們選擇的文件。 我看到了很多類似thisthisthis的問題。我看到的大多數問題(像這樣 )都要求在上傳之前預覽圖像。 我認為我不需要預覽圖像,我只想上傳它。 我該怎么做呢? 這是我當前的代碼:

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; ,還有許多其他。

在html代碼中,將輸入字段放置為id。 例如,如果要從相機上傳圖片:

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

然后在您的js代碼中,您將偵聽此元素的change事件:

  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編寫代碼,則還需要用var替換let並添加; 在行尾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM