2017-10-28 97 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;在你的线路结束。

相关问题