【问题标题】:How can I upload multiple files using vue.js and multer?如何使用 vue.js 和 multer 上传多个文件?
【发布时间】:2020-01-11 15:09:10
【问题描述】:

我可以使用 multer 上传单个文件。但是当涉及到多个文件时,它将不再起作用,并且 multer 不会捕获任何文件。

我通过 formData.append() 发送文件。但它只上传单个文件

Vue component

const formData = new FormData();
formData.append("productImg", this.imgFile);
this.$store.dispatch(POST_PRODUCT_IMAGE, formData)
    .then((response) => {
        console.log(response.data);
    })
    .catch(error => {
        console.log(error);
    })

Server file

const uploadPath = path.join(__dirname, '/../../public/uploads');
var storage = multer.diskStorage({
    destination: (req, file, callback) => {
        callback(null, uploadPath + "/garbage/productImg");
    },
    filename: (req, file, callback) => {
        var newName = Date.now() + "_" + file.originalname;
        callback(null, newName);
    }
});

const upload = multer({
    storage: storage
});

productRouter.post('/uploadProductImage', upload.any(), async (req, res) => { // Some Code })

我也是

productRouter.post('/uploadProductImage', array('productImg[]', 6), async (req, res) => { // Some Code })

我想一次将多个文件上传到我指定的文件夹。

【问题讨论】:

    标签: javascript express vue.js multer


    【解决方案1】:

    最后我找到了一个非常愚蠢的解决方案。

    在 Vue 组件文件中,我只是在添加 formData 之前使用了一个循环。像这样。

    Vue 组件

    const formData = new FormData();
    // formData.append("productImg", this.imgFile); // OLD ONE
    for (let index = 0; index < this.imgFile.length; index++) { //NEW ONE
      let file = this.imgFile[index];
      formData.append("productImg["+index+"]", file);
    }
    this.$store.dispatch(POST_PRODUCT_IMAGE, formData)
        .then((response) => {
            console.log(response.data);
        })
        .catch(error => {
            console.log(error);
        })
    

    【讨论】:

      猜你喜欢
      • 2021-04-09
      • 1970-01-01
      • 2017-01-13
      • 2019-01-26
      • 2020-05-31
      • 1970-01-01
      • 2017-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多