使用Nodejs将图像上传到Firebase

时间:2018-01-27 01:00:43

标签: node.js firebase express google-cloud-storage multer

我正在尝试将图片上传到firebase,工作正常。问题是,如果我尝试在其他电脑上使用带邮递员的api路由,则上传将无效。我调查了很多,但遗憾的是无法解决这个问题。我真的不明白为什么它只能在我的语言环境机器上运行。

const Multer  = require('multer')
const firebase = require('firebase')
const googleStorage = require('@google-cloud/storage')
const path = require('path')
const util = require('util')

let multer = Multer({
    fileFilter: function(req, file, cb) {
      checkFileType(file, cb)
    },
    storage: Multer.memoryStorage(),
    limits: {
      fileSize: 5 * 1024 * 1024 
    }
  })

  function checkFileType(file, cb){
    const filetypes = /jpeg|jpg|png|gif/
    const extname = filetypes.test(path.extname(file.originalname).toLowerCase())
    const mimetype = filetypes.test(file.mimetype)

    if(mimetype && extname){
      return cb(null, true)
    } else {
      cb('Please provide only Images!')
    }
  }

  const storage = googleStorage({
    projectId: "mybucket",
    keyFilename: "auth.json"
  })

  const bucket = storage.bucket("mybucket")

  const uploadImageToStorage = (file) => {
    let prom = new Promise((resolve, reject) => {
      if (!file) {
        reject('No image provided')
      }
      let newFileName = `${file.originalname}_${Date.now()}`

      let fileUpload = bucket.file(newFileName)

      const blobStream = fileUpload.createWriteStream({
        metadata: {
          contentType: file.mimetype
        }
      })

      blobStream.on('error', (error) => {
        reject('Something is wrong! Unable to upload at the moment.');
      })

      blobStream.on('finish', () => {
        const url = util.format(`https://storage.googleapis.com/${bucket.name}/${fileUpload.name}`);
        resolve(url)
      })

      blobStream.end(file.buffer)
    })
    return prom
}
module.exports = {
  multer,
  uploadImageToStorage
}

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。

  const storage = googleStorage({
    projectId: "mybucket",
    credentials: require('../secret/auth.json')
  })

我刚刚使用keyFilename删除了credentials。似乎导入我的auth.json作为模块是一个更好的主意。我希望我会帮助这个解决方案的人。它现在对我来说很好。