如何使用Multer Node JS将图像上传到Google Cloud

时间:2020-08-09 15:16:20

标签: javascript node.js image google-cloud-platform multer

如果存储是memoryStorage,我已经在NodeJS中使用Multer完成了上传,因为文件首先保存在缓冲区中,然后我可以从缓冲区中上传到Google Drive,

但是如果使用memoryStorage我无法重命名图像文件,

我使用multer.diskStorage,但是发布时,文件成功上传,但没有图片,文件大小变小,如10B。

这是我在函数中的代码,具有功能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

上面的代码可以成功上传到Google云端硬盘,但不能上传图片,因为大小始终为10B。

1 个答案:

答案 0 :(得分:0)

这是我在助手中创建的最终代码,在工作中,将图片上传到temp或本地的任何文件夹后,我们可以从这些位置上传到Google云

   today = datetime.now().date()
   yesterday = today - timedelta(days=1)

   start_date = date(2020, 8, 10)
   end_date = today
   day_count = (end_date - start_date).days
   day = timedelta(days=1)

   date = start_date

   results = []
   for i in range(day_count):
      date += day
  
      fields = [
         'campaign_name',
         'reach',
         'impressions',
         'frequency',
         'clicks',
         'spend',]

      params = {
        'level': 'campaign',
        'filtering': [],
        'breakdowns': [],
        'time_range': {'since': str(date),
        'until': str(date)},
        'time_increment': '1',
        'limit': 1000}

      results.append(my_account.get_insights(fields=fields,
            params=params))