Cub*_*tic 6 javascript jquery image firebase firebase-storage
我有一个输入字段,用户可以在其中选择他们想要上传的图像,然后我需要发送到云存储。问题是,我不知道如何获取他们选择的文件。我看到了很多的问题,如这个,这个,这个,我看到,像这些问题等。大多数这一个,所要求的预览图像之前上传。我认为我不需要预览图像,我只想上传它。我该怎么做呢?这是我当前的代码:
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!');
});
});
}
Run Code Online (Sandbox Code Playgroud)
为此, console.log() 给出了“未定义”。我也尝试过.files[0]代替.files;,以及许多其他人。
Ist*_*oki 12
在您的 html 代码中,您将输入字段与一个 id 一起放置。例如,如果您想从相机上传图片:
<input type="file" accept="image/*" capture="camera" id="cameraInput">
Run Code Online (Sandbox Code Playgroud)
然后在您的 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)
})
Run Code Online (Sandbox Code Playgroud)
当然,您之前需要以某种方式包含 firebase js 库。
而且如果你用旧版本的js编写,你还需要将 let 替换为 var 并添加 ; 在你的行尾。
| 归档时间: |
|
| 查看次数: |
9245 次 |
| 最近记录: |