2017-10-28 110 views
0

我有一個輸入字段,用戶可以在其中選擇要上傳的圖像,然後我需要發送到雲存儲。問題是,我不知道如何獲取他們選擇的文件。我看到很多問題,例如thisthisthis等。我看到的大多數問題(如this之一)都要求在上傳之前預覽圖像。我不認爲我需要預覽圖像,我只想上傳它。我該怎麼做呢?這是我現在的代碼:如何從輸入字段上傳圖片到firebase雲存儲?

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

回答

0

在您的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,你也需要用var和add替換let;在你的線路結束。

相關問題