3

I am able to upload a single file using multer. But when it comes to multiple files it won't work anymore and no file is caught by multer.

I send files through formData.append(). But it only uploads single file

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 })

I did also

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

I want to upload multiple files at a time to my specified folder.

1 Answer 1

1

Finally i found a solution which is very silly though.

In Vue component file i just use a loop before add in formData. Like this.

Vue Component

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);
    })
Sign up to request clarification or add additional context in comments.

1 Comment

Amazing code buddy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.