seikida
seikida

Reputation: 407

Upload an image into Firebase Storage from a callable https cloud function

I would like to upload an image into Firebase Storage from a callable https cloud function but I don't know how to do that.

const functions = require('firebase-functions');

const admin = require('firebase-admin');

admin.initializeApp();

const storageBucket = admin.storage().bucket('gs://xxxxx.appspot.com');

exports.test_upload = functions.https.onRequest(async (request, response) => {

    var base64Img = "data:image/jpeg;base64,/9j/4AAQSkZJRg...AoNDQoIC";

    let filename = new Date().getTime() + '.jpg';

    await storageRef.child('/destination/'+filename).putString(base64Img, 'data_url').then(function(snapshot) {

        snapshot.ref.getDownloadURL().then(async (url) => { 
            
            console.log(url);

        });

    });


    response.status(200).send("Done!");

});

Can you help me to understand, how to do that?

Thank you so much

UPDATE: 2020/07/22

const functions = require('firebase-functions');

const admin = require('firebase-admin');

admin.initializeApp();

const storageBucket = admin.storage().bucket('perfume-group.appspot');

const {Storage} = require('@google-cloud/storage');

const storage = new Storage({keyFilename: 'perfume-group-key.json'});

exports.test_upload = functions.https.onRequest(async (request, response) => {

    /// CAS 1: Don't works
    // Source: https://stackoverflow.com/questions/53969468/how-to-store-files-in-firebase-using-node-js

    const fileUrl = 'https://i.pinimg.com/originals/4a/9d/f8/4a9df83774219e0d02bbb9e5dc9be125.jpg';

    const opts = {
        destination: 'destination/file1.jpg',
        metadata: {
            contentType: 'image/jpeg'
        }
    };

    firebase.storage().bucket().upload(fileUrl, opts);

    //////////////////////////////////////////////////

    /// CASE 2: Don't works

    const bucket = storage.bucket('perfume-group.appspot.com');

    bucket.upload(fileUrl, {
        destination: 'destination/file2.jpg',
        metadata: {
            contentType: 'image/jpeg'
        }
    });

    //////////////////////////////////////////////////

    /// CASE 3: Don't works

    const options = {
      destination: 'destination/file3.jpg',
    };

    // Downloads the file
    await storage.bucket('perfume-group.appspot.com').file(fileUrl).download(options);

    //////////////////////////////////////////////////


    response.status(200).send("Done!");

});

is it possible to have examples that work?
Like this page: https://firebase.google.com/docs/storage/web/upload-files

I understood how to add data to the Database but to add files to the Storage it is not clear.

Why this explain don't works ? -> https://googleapis.dev/nodejs/storage/latest/Bucket.html#upload

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

await bucket.upload('https://i.pinimg.com/originals/4a/9d/f8/4a9df83774219e0d02bbb9e5dc9be125.jpg', function(err, file, apiResponse) {
      
});

After all, my storage still empty.

Upvotes: 3

Views: 4387

Answers (1)

v3rt1ag0
v3rt1ag0

Reputation: 824

Took me a while to figure it out so posting it here in case it helps others in the same boat. I am using formidable serverless to parse the request.

const functions = require("firebase-functions");
const formidable = require("formidable-serverless");
const admin = require("firebase-admin");
admin.initializeApp();

exports.uploadFile = functions.https.onRequest((req, res) => {
  var form = new formidable.IncomingForm();
  form.parse(req, async (err, fields, files) => {
    var file = files.fileToUpload;
    if (err || !file) {
      res.status(500).send(err);
      return;
    }
    var filePath = file.path;
    var filename = file.name;
    var bucket = admin.storage().bucket("nameOfBucket.appspot.com");

    const options = {
      destination: "profile/" + filename,
      contentType: "image/jpeg", //file.path
    };

    //upload image
    await bucket
      .upload(output, options)
      .catch((error) => res.status(500).send(error));
    await res.status(200).send("success");
  });
});

Html form code:

<form action="https://yourCloudFunctionsUrl.cloudfunctions.net/uploadFile" method="post" enctype="multipart/form-data">
        <input type="file" accept="image/*" name="fileToUpload" >
        <input type="submit" value="upload">
</form>

Upvotes: 5

Related Questions