我有一个输入字段,用户可以在其中选择他们想要上传的图像,然后我需要发送到云存储。问题是,我不知道如何获取他们选择的文件。我看到很多问题,比如this https://stackoverflow.com/questions/31353703/how-to-upload-image-file-from-computer-and-set-as-div-background-image-using-jqu, this https://www.codeproject.com/Questions/602912/howplustoplusgetplusfullplusfilepluspathplusfrompl, this https://stackoverflow.com/questions/22087076/how-to-make-a-simple-image-upload-using-javascript-html等等。我看到的大多数问题,比如this https://stackoverflow.com/questions/5802580/html-input-type-file-get-the-image-before-submitting-the-form一,要求在上传之前预览图像。我认为我不需要预览图像,我只想上传它。我该怎么做呢?这是我当前的代码:
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 代码中,您将侦听此元素上的更改事件:
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并add;在你的行的末尾。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)