Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload image to firebase cloud storage from input field?

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!');
    });
  });
}

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

like image 779
aravk33 Avatar asked Oct 28 '17 10:10

aravk33


1 Answers

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">

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)
  })

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

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.

like image 84
Istopopoki Avatar answered Sep 21 '22 00:09

Istopopoki