Is there a way to utilize vue.js and multer for uploading multiple files simultaneously?

I am facing an issue with multer where I can upload a single file successfully, but when attempting to upload multiple files it does not work and no files are captured by multer.

I am using formData.append() to send files, but it only manages to upload a 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 })

In my attempts to fix the issue, I also tried:

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

My ultimate goal is to be able to upload multiple files simultaneously to a specific folder.

Answer №1

At long last, I stumbled upon a solution that may seem a bit silly, but it gets the job done.

Within my Vue component file, instead of simply adding the formData as is, I decided to implement a loop. Here's how I did it:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Despite the presence of data, MongoDB is not returning any values

I am currently working on a code that utilizes $geoNear to find the closest transit stop to a given GPS coordinate. The issue I am facing is that the result sometimes returns undefined, even though I have confirmed that the data exists in the STOPS collect ...

I am unable to send out messages using socket.io

I am facing an issue while trying to create a chat room that involves passing user session data from passport and express to socket.io. However, I am unable to emit any messages as io.on does not seem to establish a connection. No error messages are being ...

"Distributing SQL Server Express along with my software: A step-by-step guide

I have created a software application that utilizes SQL Server Express. For legal clarification, I am seeking confirmation regarding the legality of my software. Users have the option to click on a button within my program that initiates the installation ...

An error notification received from the command "jspm install jquery"

As I follow the tutorial on the jspm.io site, everything goes smoothly until I reach step 3. When I try to execute jspm install jquery, an error message pops up. The error reads: warn Error on getOverride for jspm:github, retrying (2). ReferenceError: ui ...

Encountering Internal Server Error when running Node-Express app on render.com with query parameters live

Currently, I am facing an issue while attempting to execute a live route with query using my nodejs express application on render.com. Strangely, all other routes connected to the crud operations are functioning properly except for the search filter route ...

Showing JSON Array Values in a Table

I have created an array and am attempting to display its values in a table. Initially, my solution only displayed a single value from the array that matched an exact ID. You can see this implementation at (). Entering "jjones" would yield a result. I then ...

What are the recommended methods for binding a variable to an XMLHttpRequest object?

const request = new XMLHttpRequest(); request.open('GET', 'example.php'); request.customVar = 0; request.onreadystatechange = function(){ this.customVar = this.responseText.length; const text = `${this.readyState}:${this.customVar}: ...

Guide to implementing bidirectional data binding for a particular element within a dynamic array with an automatically determined index

Imagine having a JavaScript dynamic array retrieved from a database: customers = [{'id':1, 'name':'John'},{'id':2, 'name':'Tim}, ...] Accompanied by input fields: <input type='text' na ...

Avoid navigating through hidden tab indexes

Below is the HTML code that I am working with: <span tabindex="19"> </span> <span tabindex="20"> </span> <span tabindex="21"> </span> <span id="hidden" tabindex="22"> </span> <span tabindex="23"&g ...

Having trouble establishing a connection to the remote server using node js?

I have been working on integrating a third-party Recharge API. I provided them with the necessary URL, so that whenever a message is sent - whether it's a success or failure - they can update the URL accordingly. Upon checking my AWS system, everythi ...

Expressing frustration with the post not parsing the requested payload

Trying to troubleshoot an issue with a post request for user profiles. I'm sending the entire object to an Angular form from Express (stored in MongoDB), but I can't seem to get the route to read the data I sent back using body parser. Here is t ...

Leverage the power of Webpack to make Vue available globally

Currently, I am dealing with a situation in a legacy Rails application that has undergone some migration to integrate Webpacker and Vue. Additionally, we are utilizing a legacy script loaded through a CDN that also requires Vue. However, instead of bundlin ...

Displaying a div based on the response after it is received using an if/else statement

In my form, each question is on a separate page (div), with the ability to show and hide pages. If a user receives a response from the API with a status of "accepted", they are redirected to a URL. I'm currently trying to display a div if their status ...

Removing data from the controller with JQUERY AJAX in a Spring MVC application

Could someone assist me with this issue? I am trying to implement ajax and sweetalert.js using the following repository: So far, everything is working well when I use onclick = "" to call my function. However, I need guidance on how to properly utilize th ...

choosing concealed div

Struggling to target the span element within the initial item of an unsorted list, but struggling with getting the DOM structure right. <li class="chapterItem"> <a href="http://www.neuromanga.com/mangaReader.php?chapterNo=12&amp;#page ...

Firefox Style for HTML input Range

I'm encountering a CSS issue with an input-range element: <input type="range" id="difficultSelect" max="3" min="1" value="2"/> Here is the CSS code I am using: -webkit-appearance: none; z-index: 102; width: 225px; height: 5px; margin-left: 95 ...

What is the process of mapping an array of object IDs in order to retrieve the corresponding objects associated with each ID

I currently have a specific collection that stores IDs referencing objects in a separate schema. If I'm working with an array containing these IDs, what is the best way to iterate through and retrieve the corresponding object? Although I've mad ...

Guide on extracting FormData from a POST request in Node.js using Multer

I have a specific challenge where I need to store formData on a mongodb schema, using nodejs and express for the backend, along with multer as middleware. This particular formData consists of both a string and a blob. My main issue is capturing and saving ...

Increment or decrement a number using setTimeout in JavaScript

Having trouble with incrementing and decrementing a number using a timer in my code. It seems to not be working properly... let num = 0, maxNum = 5, timerFunc = function() { if (num < maxNum) { num++; console.log(num); //working f ...

Tips for determining if a key is present in local storage:

I need to set a key value, but only if it doesn't already exist. In my component1.ts file, I am assigning the key and value in the constructor. However, I want to include a condition that this action should only be taken if the key is not already pre ...