繁体   English   中英

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

[英]Busboy: upload file and accessing 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}` });
      }
    };

编辑:问题可能来自 postman 方面,它不允许同时发送多部分和 JSON 数据

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

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

2 - 在 try{} 顶部的代码中,我添加了这个 const body = {} 并在你使用这个代码片段之后

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM