Upload Images to Google Storage Engine using node.js

Upload Images to Google Storage Engine using node.js

In this article, we are going to use the multer to upload the images to the google cloud storage engine.

This will cover the basic express setup and upload functionality step by step.

Step1:

Initialize the new node.js app using the below command

npm init -y

Step2:

Install express, multer, multer-google-storage npm packages using below command

npm i -S express multer multer-google-storage

Step3:

Download the key file from your Google Cloud Platform account using the below steps.

  1. Go to your GCP console or here .
  2. Choose the project which you have created.
  3. Then navigate to IAM and Admin option in the sidebar and select Service Accounts options.
  4. Then click on the More icon at the end of your project and select Create Key.
  5. Select as JSON click create. This will create the key and the JSON file will be downloaded in the browser.

Step4:

Create the sample express server and the upload route as below:

var multer = require("multer");
var express = require("express");

var app = express();

app.post('/upload', function (req, res) {
  console.log(req);
  res.json(req.files);
});

app.listen(2000, (err) => {
  err ? console.log('Server Start Failed') : console.log('Server started');
})

Now add the multer and multer-google-storage dependencies to the upload route

var multer = require("multer");
var express = require("express");
var multerGoogleStorage = require("multer-google-storage");
var app = express();
var uploadHandler = multer({
  storage: multerGoogleStorage.storageEngine({
    autoRetry: true,
    bucket: '<bucketName>',
    projectId: '<projectId>',
    keyFilename: '<pathToKeyFile>',
    filename: (req, file, cb) => {
      cb(null, `/projectimages/${Date.now()}_${file.originalname}`);
    }
  })
});

app.post('/upload', uploadHandler.any(), function (req, res) {
  console.log(req.files);
  res.json(req.files);
});

app.listen(2000, (err) => {
  err ? console.log('Server Start Failed') : console.log('Server started');
})

bucket — Go to GCP and select the storage from the side menu. This will display all the storage buckets with their name. projectId- This can be fetched from the downloaded key file.

Final Step:

Now try calling the upload route and see the file that gets uploaded to the Storage engine in the GCP.

GitHub Repo: