我是个新手,一般都是后台开发人员。但是我想把文件上传到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数据
发布于 2021-02-05 22:14:33
最后我用这个方法实现了我一直在寻找的东西
1-在您的邮递员中使用body > formdata。然后,通过填充键/值区域,输入任意数量的字段。
2-在您的代码中,在try{}的顶部添加此const = {},并在您使用此代码片段之后添加
busboy.on(
"field",
function (
fieldname,
val,
fieldnameTruncated,
valTruncated,
encoding,
mimetype
) {
body[fieldname] = val;
}
);最后,您可以添加这样的集合
await db.collection("images").add({
url,
description: body.description,
});https://stackoverflow.com/questions/66048312
复制相似问题