Busboy:上传文件并访问 req.body

问题描述

总的来说,我是后端开发的新手。但我想将文件上传到 firebase 并且我遇到了这个名为 busboy 的乏味工具,它在上传文件时工作正常。问题虽然我想上传一个文件并在 req.body 中提取信息,但我得到 req.body 未定义。这是我的代码

    const Busboy = require("busboy");
    const path = require("path");
    const os = require("os");
    const fs = require("fs");
    const { admin,db,config } = require("../../util.js");

    exports.postimage = async (req,res) => {
      try {
        const description = req.body.description;
        const busboy = new Busboy({ headers: req.headers });
        let name;
        let image = {};
        let url;
        busboy.on("file",(fieldname,file,filename,encoding,mimetype) => {
          if (mimetype !== "image/png") {
            return res.status(400).json({
              error: "This extension is not supported. Please upload a png image",});
          }
          const extension = filename.split(".").pop();
          name = `${Math.round(Math.random() * 10000000000000)}.${extension}`;
          const filepath = path.join(os.tmpdir(),name);
          image = { filepath,mimetype };
          file.pipe(fs.createWriteStream(filepath));
        });
        busboy.on("finish",async () => {
          await admin
            .storage()
            .bucket()
            .upload(image.filepath,{
              resumable: false,metadata: {
                metadata: {
                  contentType: image.mimetype,},});
          url = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${name}?alt=media`;
          await db.collection("images").add({
            url,description,createdAt: new Date().toISOString(),});

          return res.json({ meassage: "uploaded" });
        });
        busboy.end(req.rawBody);
      } catch (e) {
        return res
          .status(500)
          .json({ error: `Error,could not upload file: ${e}` });
      }
    };

编辑: 问题可能来自邮递员方面,它不允许一次发送多部分和 JSON 数据

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)