【发布时间】:2020-08-06 04:13:35
【问题描述】:
在过去的几天里,我很难使用 busboy 在 firebase 上上传多张图片。 我想使用 3 个字段和 3 个不同的图像。所以我可以将它存储在一个文件夹中。 我还希望图像具有字段名称
我找到了一个帮助我使用 Promise.all 和 forEach 的主题,但对我没有用
- 将所有文件存储在一个数组中
var Promise = require('promise');
const Busboy = require("busboy");
const fs = require("fs");
const os = require("os");
const path = require("path");
const busboy = new Busboy({ headers: req.headers });
let imageToAdd = {};
let imagesToUpload = []
let newFileName;
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
const imageExtension = filename.split('.')[filename.split('.').length - 1];
filename = `${fieldname}.${imageExtension} `
newFileName = filename
const filepath = path.join(os.tmpdir(), filename);
imageToAdd = { file: filepath, type: mimetype };
file.pipe(fs.createWriteStream(filepath));
imagesToUpload = [...imagesToUpload, imageToAdd]
});
- 遍历 files 数组并将 Promise 存储在新数组中
- 然后等待所有的 promise 用 Promise.all 解决
busboy.on("finish", () => {
let promises = []
imagesToUpload.forEach((imageToBeUploaded) => {
promises.push(
admin
.storage()
.bucket(`${config.storageBucket}`)
.upload(imageToBeUploaded.file, {
resumable: false,
destination: `projectname/${newFileName}`,
metadata: {
metadata: {
contentType: imageToBeUploaded.type,
}
}
})
)
})
Promise.all(promises)
.then(res => {
res.status(200).json({msg: 'Successfully uploaded all images')
})
.catch(err => {
res.status(500).json({error: err.code})
})
})
busboy.end(req.rawBody);
})
只有最后一张图片存储在我的 Firebase 存储中。
有人可以帮我解决这个问题吗?
谢谢
【问题讨论】:
标签: node.js firebase firebase-storage busboy