使用多个文件字段上传多个图像

Uploads multiples images with multiples files field

过去几天,我一直在苦苦思索如何使用 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]
    });
    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 存储中。

有人可以帮我解决这个问题吗?

感谢

您的代码中只有一个 newFileName,而您有一个数组 imagesToUpload。因此,您将这些图像中的每一个上传到相同的 newFileName,并以最后完成的上传结束。

您需要保留 newFileNames 的数组,以与 imagesToUpload 的数组匹配。

类似于:

const busboy = new Busboy({ headers: req.headers });
let imageToAdd = {};
let imagesToUpload = []
let newFileNames = [];

busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
    const imageExtension =  filename.split('.')[filename.split('.').length - 1];
    filename = `${fieldname}.${imageExtension} `
    const filepath = path.join(os.tmpdir(), filename);
    imageToAdd = { file: filepath, type: mimetype };
    file.pipe(fs.createWriteStream(filepath));

    imagesToUpload.push(imageToAdd);
    newFileNames.push(filename);
});

...

busboy.on("finish", () => {
    let promises = imagesToUpload.map((imageToBeUploaded, index) => {
        admin
        .storage()
        .bucket(`${config.storageBucket}`)
        .upload(imageToBeUploaded.file, {
            resumable: false,
            destination: `projectname/${newFileNames[index]}`,
            metadata: {
                metadata: {
                  contentType: imageToBeUploaded.type,
                }
            }
        })          
    }) 
    Promise.all(promises)
      ...