When utilizing the multipart/form-data content type in a form, the files being sent are transmitted as blank

I am currently developing a VueJS component that functions as a form to collect user information and enable multiple image uploads.

The form is set with enctype="multipart/form-data" and exhibits the following structure :

<template>
  <div>        
    <form enctype="multipart/form-data" novalidate>
        <label>Name</label>
        <input type="text" v-model="name">
        <label>Surname</label>
        <input type="text" v-model="surname">
        <label>Description</label>
        <input type="text" v-model="description">        
        <input 
         type="file"
         id="resources"
         ref="images"
         multiple 
         @change="handleFileUpload()"
         accept="image/*">   

    <button @click="clear">Clear Form</button>
     <button @click="submit"> Submit </button>
        </div>
      </form>
 </template>

My handleFileUpload() function performs this action :

this.images = this.$refs.images.files

The submit function is structured in this manner :

submit () {
// Saves image to formData 
let formData = new FormData()

for( var i = 0; i < this.images.length; i++ ){
   let img = this.images[i];
   formData.append('image[' + i + ']', img);
}

let newUser = {
  name : this.name,
  surname:this.surname,
  description : this.description,
  images : formData
}

axios.post('http://localhost:3000/api/users', newUser)
 .then(() => {console.log('ok')})
 .catch((err) => {console.log(err)})
}

My issue lies in the fact that the images field of newUser is being received as an empty object. I am uncertain if I should send formData in that way or if there might be an issue with the express API I've created for this purpose :

var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(cors());


let users = [];

app.post('/api/users',(req,res) => {
  const newUser = req.body;
  users.push(newUser);
  res.json(users);
});

Logging newUser in the API results in this output :

{ name: 'test',      
  surname: 'test',
  description: 'test',
  images: {} }

Answer №1

If you're new to nodejs, you may run into the issue of body-parser not supporting multipart/form-data as mentioned in their documentation.

To handle this, you will need to seek out some middleware that can manage multipart bodies for you. The body-parser documentation suggests a few options:

Since body-parser does not handle multipart bodies due to their complex and typically large nature, consider using the following modules:

Each of these libraries will have its own way of working, so make sure to refer to their documentation when constructing your images object on the server side.

Answer №2

Dealing with the issue of an empty request body in my API server project was quite a challenge. My goal was to post multipart-form data containing both string/text data and an image to a backend restful API server. Initially, I believed that simply passing the data using formData object through Axios would suffice. However, I soon found myself facing frustration as the backend API project continued to receive empty request bodies. Fortunately, after conducting thorough research through various articles, StackOverflow, and YouTube, I successfully developed a fully functional Node.js program. No more issues with empty request body data!

In order to pass multipart/form-data from the client to the server, I discovered that several middlewares and node/Java objects need to be utilized:

  • For the server-side API project: Implementing {multer, body-parser} middleware.
  • For the client app project: Utilizing formData and axios.

Below are the snippets of my working codes (written in Node.js using Visual Studio Code):

// Within my (server backend API) node project: /src/routes/products/index.js

// Code snippet here

Now moving on to (server backend API) /src/app.js:

// Code snippet here

Continuing on to (server backend API) /src/index.js:

// Code snippet here

The code for ProductController in the (backend API): /src/controller/Products.js:

// Code snippet here

Finally, in my client app project, I utilized Axios and formData to send POST requests to the backend API server.

Here is an excerpt of the code used in the front-end client app for posting:

// Code snippet here

Furthermore, a function can be implemented to extract image data from an input HTML event:

// Code snippet here

I trust that these provided codes will assist individuals encountering similar challenges with empty request body problems.

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

Can I add the object to the DOM and hold off on executing any events until the next

Just came across this intriguing interview question (shown below). Could someone please provide an explanation of the question and then offer a solution? Develop a function that takes an object and adds it to the DOM, ensuring that events are stored unt ...

Transitioning from using a jQuery get request to utilizing Vue.js

Looking to transition from JQuery-based js to Vue as a newcomer to JavaScript. Seeking guidance on making a get request and displaying the retrieved data. What approach would you recommend for this task? Here's the HTML snippet: <div> <di ...

Retrieving information from an Express.js API using React.js. Postman requests are successfully communicating with the API

Hey there, I'm facing a little issue and could use some help. I have an Express application that is working perfectly with requests from Postman (adding, deleting, etc.). Now, I want to connect my client side (React.js) with the existing API using the ...

Creating an angular controller in a template based on certain conditions

When working with Angular.js, I'm attempting the following: index.html <div class="data-tabs-sms-scroll" ng-show="question.type == 'open'" ng-controller="AudioMessagesCtrl" ng-include="'/templates/audioMessages.html' ...

Sharing parameters between functions in JavaScript

I have a working code but I want to modify the function getLocation to accept 2 arguments that will be passed to getDistanceFromLatLonInKm within the ajmo function. Currently, getDistanceFromLatLonInKm has hardcoded arguments and I would like to use variab ...

Error in React Typescript Order Form when recalculating on change

When creating an order form with React TypeScript, users can input the quantity, unit price, and select whether the item is taxable. In this simplified example, only 1 or 2 items can be added, but in the final version, users will be able to add 10-15 item ...

What is the best way to paginate a dynamically updated data table using AJAX in Laravel?

I'm currently facing an issue with rendering a Blade template in Laravel. The template includes an HTML table populated with data fetched via AJAX, and I need to implement manual pagination using Laravel's LengthAwarePaginator. The main Blade fi ...

Tips for disregarding global CSS in Nuxt.js?

I've been utilizing a boilerplate that integrates with the CoreUI template from GitHub, and it's been working well. However, I am now looking to customize my index page with a unique style, and I'm encountering issues where the global CSS fr ...

HighStocks should show categories instead of dates

The zoom function in HighCharts is what drew me to it initially. Everything was working perfectly until I encountered an issue that I can't seem to resolve. Here's my code snippet: http://jsfiddle.net/ma50685a/16/ $(function() { // Crea ...

methods for transforming JSON array output objects into individual non-array values

I'm facing an issue with a JSON result that contains latitude and longitude as an array like [13.0801721, 80.2838331]. I need help in converting this to comma-separated values without the array brackets, similar to 13.0801721, 80.2838331. This is my ...

Encountering a FileNotFound Error when attempting to access a file in a different directory using Python

\parentDirectory \subdr1 -testfile.txt \subdr2 \childdir -data.json -config.pickle -jsonReader.py I am trying to access data.json from jsonReader.py in Python by using the following ...

Retrieving the CSS property values for a specific element using Selenium

Imagine a scenario where I locate an element by its XPath using: WebElement element = driver.findElement(By.xpath("specific XPath")); While I can retrieve the value of a single CSS property with element.getCssValue("specific property"), is there a way to ...

Clone a specific link within a div using jQuery only one time

I have a group of divs and I want to copy the link from the first div and put it into the last div (mobile-link). Currently, it is either duplicating all the links and inserting them all at once, or if I use :eq(0), it's placing the first link in each ...

TypeScript does not perform type checking on arrays created using the Array() constructor and filled with the fill method

Using TypeScript version 2.4.2, compiled with the --target ES6 option has interesting results. For example, when using this line of code: var coins: { coin: number}[] = [1,1,1] TypeScript throws an error: Error TS2322: Type 'number[]' is no ...

Trouble with React component not updating after URL parameter change despite utilizing useEffect hook for data fetching

Let's address an important issue: I've created a component that needs to maintain the same structure across approximately 25 different items or pages. To achieve this in React, I am dynamically passing URL parameters into my API request as shown ...

Having trouble transferring data from Flask to JavaScript as JSON when using a separate .js file

In my templates/index.html file, I have the following code: <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <style> </style> </head> & ...

Adding custom data attributes to HTML tags in Vue.js

I have a question regarding adding a data attribute to the <html> element in vue.js (v2). I haven't been able to find any guidance on how to do this in the auto generated code or the documentation. The end goal is to achieve this desired output ...

Utilizing inputRef in conjunction with MUI's useAutocomplete

Is there a way to pass the "inputRef" to Material UI's useAutocomplete? I'm looking to set a custom reference on the input, but the getInputProps() method from useAutocomplete already requires its own reference. I've attempted various appr ...

The deep reactivity feature in Vue3 is functioning well, however, an error is being

I am currently using the composition API to fetch data from Firestore. While the render view is working fine, I am encountering some errors in the console and facing issues with Vue Router functionality. This might be due to deep reactivity in Vue. Here is ...

What is the process for creating a progress bar in PixiJS?

Can someone guide me on creating a progress bar similar to the one in PixiJS? Screenshot ...