首页 > 解决方案 > 使用 BusBoy for firebase 的 FormData 在服务中有效,但在部署中无效

问题描述

情况

我有一个更新用户图像的 firebase 功能。

问题

当我使用 本地运行我的函数时firebase serve,我使用 Postman 成功地将图像上传到 Firestore。但是,当我运行firebase deploy并尝试使用 Postman 上传图像时,我收到 500 内部服务器错误。其他功能(不处理 FormData,只处理 json)在我部署它们时工作得很好。

我不明白为什么它在本地工作,但在我做完全相同的事情时却不能在部署时工作。不确定这是否是我缺少的配置中的某些内容,或者我做错了什么。任何帮助,将不胜感激!

代码 users.js

const { admin, db, firebase } = require('../util/admin');
const config = require('../util/config');

exports.postUserImage = (req, res) => {
  const BusBoy = require('busboy');
  const path = require('path');
  const os = require('os');
  const fs = require('fs');

  let imgFileName;
  let imgToBeUploaded = {};
  const busboy = new BusBoy({ headers: req.headers });

  busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
    // Invalid file type
    if (mimetype !== 'image/jpeg' && mimetype !== 'image/png') {
      return res.status(400).json({ error: 'Invalid file type' });
    }
    // Extract img extension
    const imgDotLength = filename.split('.').length;
    const imgExtension = filename.split('.')[imgDotLength - 1];
    // Create img file name
    imgFileName = `${Math.round(Math.random() * 1000000)}.${imgExtension}`;
    // Create img path
    const filepath = path.join(os.tmpdir(), imgFileName);
    // Create img object to be uploaded
    imgToBeUploaded = { filepath, mimetype };
    // Use file system to create the file
    file.pipe(fs.createWriteStream(filepath));
  });
  busboy.on('finish', () => {
    admin
      .storage()
      .bucket()
      .upload(imgToBeUploaded.filepath, {
        resumable: false,
        metadata: {
          metadata: {
            contentType: imgToBeUploaded.mimetype
          }
        }
      })
      .then(() => {
        // Create img url to add to our user
        const imgUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imgFileName}?alt=media`;
        // Add img url to user document
        return db.doc(`/users/${req.user.handle}`).update({ imgUrl });
      })
      .then(() => {
        return res.json({ message: 'Image uploaded succesfully' });
      })
      .catch((err) => {
        console.error(err);
        return res.status(500).json({ error });
      });
  });
  busboy.end(req.rawBody);
};

index.js

const { app, functions } = require('./util/admin');
const FirebaseAuth = require('./util/firebaseAuth');
const {
  postUserImage,
} = require('./handlers/users');
app.post('/user/image', FirebaseAuth, postUserImage);

标签: firebasegoogle-cloud-firestorebusboy

解决方案


推荐阅读