Search code examples
javascriptnode.jsimagegoogle-cloud-platformmulter

How to upload image to Google Cloud with multer node js


I have done upload using Multer in NodeJS if storage is memoryStorage, since file is save in buffer first, and than from buffer I can upload to Google Drive,

But if using memoryStorage I can not rename image file,

I using multer.diskStorage but when I post, file is succeed upload but not the picture, file size become small like 10B.

this is my code in helper with function uploadImage

const util = require('util')
const gc = require('../config/')
const bucket = gc.bucket('jsimage')//bucket name

const { format } = util

const uploadImage = (file) => new Promise((resolve, reject) => {
  console.log(file);
  //const { originalname, buffer } = file
  const { filename, destination } = file

  //const blob = bucket.file(originalname.replace(/ /g, "_"))
  const blob = bucket.file(filename)
  const blobStream = blob.createWriteStream({
    resumable: false
  })

  blobStream.on('finish', () => {
    const publicUrl = format(
      `https://storage.googleapis.com/${bucket.name}/${blob.name}`
    )
    resolve(publicUrl)
  })
  .on('error', () => {
    reject(`Unable to upload image, something went wrong`)
  })
  //.end(buffer)
  .end(destination)

})

module.exports = uploadImage

with code above I succeed to upload in Google Drive but not the picture, since size is always 10B.


Solution

  • in this example, after the picture is uploaded to temp or any local folder, we can upload it to google cloud.

    const util = require('util')
    const gc = require('../config/')
    const bucket = gc.bucket('jsimage')//bucket name di google drive
    const path = require('path')
    
    const { format } = util
    
    // promises are built right away, so there's no need for then to resolve and catch for errors
    const uploadImage = (file) => new Promise((resolve, reject) => {
      //console.log(file);
      const {filename} = file;
      const picture = path.join(__dirname,'../uploads/',filename);
    
      // This is the upload command
      bucket.upload(picture);
    
      // This is sent to return
      const publicUrl = format(
        `https://storage.googleapis.com/${bucket.name}/${filename}`
      )
    
      resolve(publicUrl)
    
      reject(err=>(err))
    
    })
    
    module.exports = uploadImage