Home > Net >  Simultaneously uploading image to storage and data for the image in the database
Simultaneously uploading image to storage and data for the image in the database

Time:10-19

I am currently working on my first ever project with React.js - building an online shop. I am using Firebase Storage to upload the images of the products. I am able to upload them and successfully get their urls with another request after that.

Is it possible to get the url right when the upload is completed? I looked trough the documentation on uploadBytes function in hope that it returns a url that can be associated with the image, but it does not.

I want to upload the picture and know its url so that I can upload additional information to the db such as price, quantity, etc. using it's url as a reference and later on fetch the information from both the storage and db based on that url.

CodePudding user response:

The uploadBytes() method returns a Promise containing an UploadResult Object which has two properties:

  • metadata, which contains the metadata sent back from the server;
  • ref, the reference that spawned this upload.

Therefore you can use the ref property to get the download URL. (Or you can directly use the reference you passed to the uploadBytes() method, since it is the same!)

For example:

import { getStorage, ref, uploadBytes } from "firebase/storage";

const storage = getStorage();
const storageRef = ref(storage, 'some-child');

const bytes = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21]);  // Example
uploadBytes(storageRef, bytes)
.then((uploadResult) => {
  return getDownloadURL(uploadResult.ref)
})
.then((downloadURL) => {
      console.log('File available at', downloadURL);
});
  • Related