【问题标题】:Issue uploading image to Firebase with Nodejs使用 Nodejs 将图像上传到 Firebase 的问题
【发布时间】:2018-01-28 09:33:24
【问题描述】:

我正在尝试将图像上传到运行良好的 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
}

【问题讨论】:

  • 这个是纯node.js,还是部署到Cloud Functions?
  • 带有firebase sdk的纯nodejs

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


【解决方案1】:

我解决了这个问题。

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

我刚刚删除了 keyFilenamecredentials。似乎将我的auth.json 作为模块导入是一个更好的主意。我希望我能帮助某人解决这个问题。现在对我来说很好。

【讨论】:

    猜你喜欢
    • 2017-11-21
    • 2019-08-31
    • 2019-08-23
    • 2017-04-15
    • 2022-08-13
    • 2021-05-12
    • 2018-04-24
    • 2020-06-21
    • 2021-04-27
    相关资源
    最近更新 更多