由于某种原因,我将图像上传到 firebase 的代码根本无法工作。
我尝试了多个不同的包来上传,例如:busboy、multer、formidable、express file parser,但似乎没有任何效果,我通常或多或少会遇到相同的错误,这就是:
Multer error: Error: Unexpected end of form
at Multipart._final (/Users/xxx/Desktop/xxx/backend/functions/node_modules/busboy/lib/types/multipart.js:588:17)
at prefinish (node:internal/streams/writable:907:14)
at finishMaybe (node:internal/streams/writable:921:5)
at Writable.end (node:internal/streams/writable:836:5)
at onend (node:internal/streams/readable:946:10)
at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
storageErrors: []
}
这是我的功能代码:
// Multer setup for handling file uploads (5MB limit)
const upload = multer({
storage: multer.memoryStorage(), // Store the file in memory
limits: { fileSize: 5 * 1024 * 1024 }, // Limit file size to 5MB
});
// Cloud Function to handle image upload
exports.updateClientProfileImg = functions.https.onRequest((req, res) => {
upload.single("image")(req, res, async (err) => {
if (err) {
console.error("Multer error:", err);
return res
.status(400)
.json({ error: `File upload error: ${err.message}` });
}
const file = req.file;
if (!file) {
console.error("No file uploaded.");
return res.status(400).json({ error: "No file uploaded" });
}
try {
console.log("File uploaded:", file);
const fileUpload = bucket.file(file.originalname);
// Create a stream and upload the file
const stream = Readable.from(file.buffer);
await new Promise((resolve, reject) => {
stream
.pipe(
fileUpload.createWriteStream({
metadata: { contentType: file.mimetype },
})
)
.on("finish", resolve)
.on("error", reject);
});
// Make the file public and generate the URL
await fileUpload.makePublic();
const imageUrl = `https://storage.googleapis.com/${bucket.name}/${fileUpload.name}`;
return res.status(200).json({
message: "Image uploaded successfully",
imageUrl: imageUrl,
});
} catch (error) {
console.error("Error uploading image:", error);
return res.status(500).json({ error: "Failed to upload image" });
}
});
});
这只是 multer,但我使用其他包的其他代码看起来相对相同。
有人有适用于最新版本的 Firebase 和 Node.js v20 的解决方案吗?
我正在开发一个使用 Firebase 函数的项目,并尝试实现 Multer,但它一直抛出相同的错误。
我最终使用了这个依赖项
express-multipart-file-parser
https://github.com/cristovao-trevisan/express-multipart-file-parser,我终于能够处理multipart/form-data请求中的文件了。