Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading a form posted image buffer to Cloud Storage with Firebase Functions

Here's my cloud function. It's supposed to get an http posted image and upload it to storage, returning the url.

exports.uploadImageToEditor = functions.https.onRequest((req, res) => {
        const img = JSON.parse(JSON.stringify(req.body));
        const bucket = admin.storage().bucket();

        return bucket.file('blog/foo.jpg').save(img.data, { 
          resumable: false, 
          metadata: { 
            contentType: 'image/jpeg' 
          } 
        })
          .then(() => {
              return cors(req, res, () => {
                  res.status(200).send({ "url": bucket.file('foo.jpg').getSignedUrl()});
                });
            });
    });

This is how the image is actually sent in the client:

uploadImage(file, endPoint) {
        if (!endPoint) {
            throw new Error('Image Endpoint isn`t provided or invalid');
        }
        const                  formData = new FormData();
        if (file) {
            formData.append('file', file);
            const                  req = new HttpRequest('POST', endPoint, formData, {
                reportProgress: true
            });
            return this._http.request(req);
        }
        else {
            throw new Error('Invalid Image');
        }
    }
like image 337
cerealex Avatar asked Jan 27 '23 21:01

cerealex


2 Answers

I think you're probably looking for the save() method on File in the Admin SDK.

const bucket = admin.storage().bucket()
  .file('my-file.jpg').save(blob)
  .then(() => { /* ... */ });
like image 200
Michael Bleigh Avatar answered Feb 09 '23 00:02

Michael Bleigh


You can also get back information about the file this way.

export const uploadImage = async (destination: string, image: Buffer) => {
  const file = storage.bucket().file(destination);
  await file.save(image, { contentType: yourContentType });
  return file.publicUrl();
};
like image 21
Daniel Suchan Avatar answered Feb 09 '23 01:02

Daniel Suchan