File Uploads with Express.js 4.0+

Ricky Romero
2 min readJul 6, 2018

--

This is how I uploaded a CSV file using node.js, express.js, and Postman.

Setup Postman

Postman is a powerful HTTP client for testing web services. This is what I use for testing my express api requests.

Setup

Set method type to POST.

Then select Body -> form-data -> Enter your parameter name (file according to your code)

On right side next to value column, there will be dropdown “text, file”, select File. choose your file and post it.

Setup express.js

Note

I will skip to where you already have express setup and waiting for the POST request to come.

If you want to know how to setup Express.js and mongoDB follow my ‘How to setup Express.js and MongoDB’ post.

Install multer

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files.

$ npm install --save multer

Usage

Multer adds a body object and a file or files object to the request object. The body object contains the values of the text fields of the form, the file or files object contains the files uploaded via the form.

Add multer to your file.

Next, you need to tell your Express app to use multer. In your file, add a require as follows:

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

Here we will receive the POST request. In this route, you can now access the properties of the file that has been uploaded using the req.file.

router.post('/upload', upload.single('statement'), (req, res) => {   console.log(`new upload = ${req.file.filename}\n`);   console.log(req.file);   res.json({ msg: 'Upload Works' });});

output:

new upload = 8b17aaf1a0b555a36b822f1e912da383{ fieldname: 'statement',
originalname: '06-16.csv',
encoding: '7bit',
mimetype: 'text/csv',
destination: 'uploads/',
filename: '8b17aaf1a0b555a36b822f1e912da383',
path: 'uploads/8b17aaf1a0b555a36b822f1e912da383',
size: 4498 }

The path property will show you where the uploaded file has been stored on your server.

Thank you,

Ricky Romero

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ricky Romero
Ricky Romero

Written by Ricky Romero

Software Engineer | 📍Los Angeles, CA

No responses yet

Write a response