【问题标题】:Uploads multiples images with multiples files field上传具有多个文件字段的多个图像
【发布时间】: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


    【解决方案1】:

    您的代码中只有一个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)
          ...
    

    【讨论】:

    • 成功了!非常感谢您的快速回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    相关资源
    最近更新 更多