简体   繁体   中英

How to upload an image of File type to Firebase Storage from Node.js with the Admin SDK

I have Angular running on the FrontEnd and Firebase Admin SDK for Node.js on the BackEnd.
What I want to achieve is to allow the user to select an image from his computer, using a simple <input> of type file . When I receive the user image which is of type File on the Angular side, I want to send this to my Node.js server and let him upload it to the Firebase Storage.
Here's how I'm sending the image to Node.js:

  method(imageInput): void {
    const image: File = imageInput.files[0];
    const reader = new FileReader();

    reader.addEventListener('load', (event: any) => {
      const imageData = {
        source: event.target.result,
        file: image
      }

      this.myService.uploadImage(imageData.file).subscribe(
        (res) => {
          // image sent successfully 
        },
        (err) => {
           // error
        })
    });

    reader.readAsDataURL(image);
  }

So on the Node.js side I don't see a way to upload this image.
I'm trying:

      admin.storage().bucket().upload(imageFromAngular, { --> Here's the problem
        destination: "someDestination/",
        contentType: "image/png",
        metadata: {
          contentType: "image/png"
        }
    }).then(() => { 
        // send successful response
    }).catch(err => {
       // send error response
    });

The issue comes from the fact that the upload method only takes as a parameter the path to the image and the options. However in this case I can't pass the path to the image, rather I can pass the image itself. I read this - https://googleapis.dev/nodejs/storage/latest/ but I couldn't find anything that would suit my needs.

What would be the correct way to do this ?

Update:

Here's a more detailed explanation to the approach I took:

I'm using the arrayBuffer method of the image File inside my method . This method returns a promise of type ArrayBuffer. I get the value and send it to my Server.
The Server uses Buffer.from(ArrayBuffer, 'base64') to convert the data and then I can safely use the save API ( https://googleapis.dev/nodejs/storage/latest/File.html#save ).

To get the image later on I use download - (https://googleapis.dev/nodejs/storage/latest/File.html#download ).

You can write a byte stream (or a Buffer ) to Cloud Storage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM