微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 数据

解决方法

我最终使用此解决方法来实现我一直在寻找的东西

1- 在您的邮递员中使用 body > formdata。然后通过填充键/值区域来放置任意数量的字段

2- 在您在代码顶部的 try{} 我添加了这个 常量体 = {} 并在您使用此代码片段后

 busboy.on(
  "field",function (
    fieldname,val,fieldnameTruncated,valTruncated,encoding,mimetype
  ) {
    body[fieldname] = val;
  }
);

最后,你可以像这样添加集合

  await db.collection("images").add({
   url,description: body.description,});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。