如何从输入字段将图像上传到Firebase云存储? [英] How to upload image to firebase cloud storage from input field?

查看:52
本文介绍了如何从输入字段将图像上传到Firebase云存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字段,用户可以在其中选择要上传的图像,然后将其发送到云存储.问题是,我不知道如何获取他们选择的文件.我看到了很多类似这个上传之前.我认为我不需要预览图像,我只想上传它.我该怎么做呢?这是我当前的代码:

I have an input field, where users can choose what image they want to upload, and then I need to send to cloud storage. The problem is, I don't know how to get the file they selected. I saw a lot questions like this, this, this, etc. Most of the questions I saw, like this one, are asking for previewing the images BEFORE uploading. I don't think I need to preview the image, i just want to upload it. How do I do this? Here is my current code:

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; 以及许多其他方法.

The console.log() for this is giving "undefined". I also tried .files[0] instead of .files;, and many others.

推荐答案

在html代码中,将输入字段放置为id.例如,如果您要从相机上传图片:

In your html code, you place the input field with a an id. For example, if you want to upload a picture from the camera:

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

然后在您的js代码中,您将侦听此元素的更改事件:

Then in your js code, you will listen to change events on this element :

  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库.

Of course you need to have somehow included the firebase js library before.

如果您使用旧版js编写代码,则还需要用var替换let并添加;在行尾.

And if you write in an older version of js, you also need to replace the let with var and add ; at the end of your lines.

这篇关于如何从输入字段将图像上传到Firebase云存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆