Using Express JS to implement a post method for multipart form data transmission

I recently attempted to send form data to my express js server. Below is the code snippet from my pug file:

form(action="/profile" method="post" enctype="multipart/form-data")
 input(type="file" accept="image/*" name="profileimage")
 input(type="text" name="username")
 input(type="submit" value="Upload")

Afterwards, I tried to access the post data using req.body in my server-side JavaScript file (profile.js):

router.post('/', function (req, res) {
  console.log('Body- ' + JSON.stringify(req.body));
});

However, when I checked the console, this was the result: body- {}

Interestingly, I noticed that if I remove enctype="multipart/form-data" from the form declaration like

form(action="/profile" method="post")
, then I am able to successfully retrieve the posted data in the console.

Answer №1

If you're looking to handle multipart form data, consider using a middleware like multer, which is highly popular.

You can download it from: https://github.com/expressjs/multer

To implement it:

  1. Start by adding it to your modules with npm install --save multer in the main project directory

  2. Then import it into your .js file using var multer = require('multer');

  3. Specify the upload directory by setting the dest parameter in the multer constructor:

    var upload = multer({ dest: 'uploads/' });

  4. Lastly, include it as middleware in your POST function like this:

    router.post('/', upload, function (req, res) {
      console.log('Body- ' + JSON.stringify(req.body));
    });
    

Make sure to refer to the documentation on their GitHub repository for more information.

Answer №2

express-formidable module is great for handling post data on the server. To install express-formidable, use this command npm install express-formidable. Here's a sample code snippet:

let express = require('express');
let app = express();
let formidable = require('express-formidable');
let path = require('path');

app.use(formidable({
  encoding: 'utf-8',
  uploadDir: path.join(__dirname, 'uploads'),
  multiples: true,
  keepExtensions: true// req.files to be arrays of files
}));

app.post('/uploads',function(req,res){
  console.log('Files '+JSON.stringify(req.files));// contains data about file fields
  console.log('Fields '+JSON.stringify(req.fields));//contains data about non-file fields
});

Make sure to create a folder uploads in your project root directory. File-related data will be in req.files, and non-file data will be in req.fields. I've tested it with ejs templating engine, but it should also work well with pug. For more information about express-formidable, check out This Link.

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

Is it possible to display data on a webpage without using dynamic content, or do I need to rely on JavaScript

Imagine a scenario where I have a single-page website and I want to optimize the loading time by only displaying content below the fold when the user clicks on a link to access it. However, I don't want users with disabled JavaScript to miss out on th ...

"Encountered an error while attempting to save data to MongoDB: Unable to insert a single buffer of 10,

I have checked all the following things: IP whitelist Async function try/catch Account password Node.js version However, I am still encountering the error. Code for MongoDB connection: const connectDB = async() =>{ await mongoose.createConnectio ...

How to create a transparent background on a canvas

Looking for help with analyzing my HTML, CSS, and JavaScript (THREE.js) code to achieve the desired output mentioned in the title. //**MY HTML CODE** <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&qu ...

Running NPM module via Cordova

After developing an app using cordova, I encountered a challenge where I needed to incorporate a node module that lacked a client-side equivalent due to file write stream requirements. My solution involved utilizing Cordova hooks by implementing an app_run ...

Exporting JSON data to CSV or XLS does not result in a saved file when using Internet Explorer

Presented below is the service I offer: angular.module('LBTable').service('exportTable', function () { function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel, fileName) { //If JSONData isn't an object, parse the ...

Utilizing PostgreSQL with Node JS Express for Powerful Datatables

Seeking guidance as a newbie here. I've taken on the challenge of creating my first full-stack app. My goal is to connect my express app and PostgreSQL database with Datatables. The API successfully fetches the data and logs it in the console, but the ...

Employing ajax with dynamically created buttons in PHP

I'm struggling to figure out what to search for in this situation. I've tried piecing together code from others, but it's just not working for me. My ajax function successfully retrieves data from a database through a php page and displays ...

The operation of "grunt build" results in a Lexer Error, causing the ng-include

After deploying my unminified code successfully, I proceed to run grunt build and deploy from the dist folder. However, upon checking one of the pages, I encounter a breakage with an error in the console: Error: [$parse:lexerr] Lexer Error: Unexpected nex ...

Tips for executing getJSON requests one after the other

My goal is to showcase a weather forecast for a specific date on my website. Here are excerpts from the code I've used on a trial page that isn't functioning correctly: <script> function displayWeather(date){ $.getJSON(url + apiKey + "/" ...

Trouble with HTML2PDF.js - download not being initiated

Currently, I am utilizing html2pdf.js in my project by following this tutorial: https://github.com/eKoopmans/html2pdf.js However, I've encountered an issue where despite implementing everything as instructed, the download prompt for the specified div ...

Transferring information from an Express.js request to a form

In my current login system, the user inputs their information and upon submission, I validate it using express. If the information is not valid, I send an error message using res.send. However, I am now trying to figure out how to redirect back to the fo ...

`Where to include controller.js scripts in an Angular application`

As I dive into learning angular.js with .NET MVC, one major issue that keeps coming up is the fact that many tutorials advise referencing multiple controllers and services in the main (_Layout) page, which can make it quite messy. Although it may seem sim ...

Vue: Utilizing computed properties to monitor changes in offsetHeight of elements

I am working on a component that requires an array of 50 objects to be passed as a prop. <template> <div v-for="(item,index) in items" ref="items" :key="index"gt; // </div> </template> props: ...

Issue encountered when attempting to push jQuery AJAX requests into an array

I'm attempting to store ajax requests in an array called deferreds. However, I'm consistently encountering the error message below: Uncaught SyntaxError: missing ) after argument list As a reference, I've been using this guide: Pass in an ...

What is the purpose of parsing my array if they appear identical in the console?

While working on a D3 component, I came across an interesting question. Why do different arrays require different data treatment even if they all contain the same information? In the first case, I have a 'hardcoded' array that looks like this: ...

Showcase a sizable picture broken down into smaller sections

I am interested in creating a mapping application similar to Google Maps that can asynchronously load images from the backend. I am seeking guidance on where to begin and how to proceed in this endeavor. The ultimate goal is to have the image displayed w ...

Challenges surrounding jQuery's .before

Currently, I am in the process of creating a simple carousel consisting of 4 divs. The carousel is utilizing 2 jQuery functions to position a div at either the first or last slot. The transitions being used are only alpha transitions as there is no need fo ...

Tips for Successfully Sending Vue Data in Axios POST Call

I'm struggling to pass Vue data to an axios.post request. Using the Vue template doesn't seem to work. How can I successfully pass the Data? Here is my Code: <body> <div id="app" class="container"> <div> ...

Formik causing malfunction in MUI DatePicker functionality

In my React project, I am using Formik to manage form processing and MUI UI components for the user interface. While I can select the day and month, I'm experiencing an issue with the year part not updating. Even when I manually type in a year in the ...

Can someone guide me on how to extract checkbox values in a post method using Angular

I'm facing an issue with a table that contains a list of rules. Whenever the checkboxes are clicked, I want them to send a "true" value to an API endpoint. However, I keep receiving an error stating that the "associated_rule" is undefined. After tryi ...