1
votes

When I use an npm package like google-cloud or multer-gcs to upload a file to firebase storage bucket (that uses google cloud storage under the hood..) the file gets uploaded. However, the file does not show and image type(MIME). Also, how do I use the image in my node.js application?

Here is the code to upload image to firebase bucket. Used multer to handle file upload..

var path = require('path');
var multer = require('multer');
var gcs = require( 'multer-gcs' );

var storage = gcs({
    filename    : function( req, file, cb ) {
        cb( null, file.fieldname + '-' + Date.now() + path.extname(file.originalname).toLowerCase());
    },
    bucket      : 'p****n-bcXX3.appspot.com', // Required : bucket name to upload 
    projectId   : 'p****n-bcXX3', // Required : Google project ID 
    keyFilename: './p****n-5cbc725XXXXd.json', // Required : JSON credentials file for Google Cloud Storage 
    acl : 'publicread' // Optional : Defaults to private 
});

In my routes:

router.post('/food/create', [authChecker, gcsUpload.single('food_image')], function(req, res, next) {
    Controllers.create_food(req, res);
});

When I upload file directly to the bucket, type shows clearly. What's the catch here? enter image description here

2

2 Answers

1
votes

It looks like multer-gcs doesn't support the ability to add custom metadata to a file. If you use gcloud directly, you'd do something like this:

var options = {
  destination: 'new-image.png',
  metadata: {
    contentType: 'image/png'
  }
};

bucket.upload('local-image.png', options, function(err, file) {
  // Your bucket now contains:
  // - "new-image.png" (with the contents of `local-image.png')

  // `file` is an instance of a File object that refers to your new file.
});

I'd file an issue with the developer of multer and ask them to support metadata uploads along side blob uploads, especially since gcloud already supports the ability to do this.

0
votes

Here is what I am doing now to handle the file upload.

req.file.modifiedname = (Math.random().toString(36)+'00000000000000000').slice(2, 10) + Date.now() + path.extname(req.file.originalname);
var options = {
  metadata: {
    contentType: req.file.mimetype
  },
  predefinedAcl : 'publicread'
};

var blob = bucket.file(req.file.modifiedname);
var blobStream = blob.createWriteStream(options);

blobStream.on('error', function (err) {
  return next(err);
});

blobStream.on('finish', function() {
  publicUrl = format(
    'https://storage.googleapis.com/%s/%s',
    bucket.name, blob.name
  );
  req.file.gcsfileurl = publicUrl;
  console.log(req.file.gcsfileurl);
  next();
});

blobStream.end(req.file.buffer);