node.js : file upload via express and multer

Form-based File Upload in HTML


Fast, unopinionated, minimalist web framework for node.


Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.
NOTE: Multer will not process any form which is not multipart (multipart/form-data).

Client Codes(index.html)

<script type="text/javascript">
function upload(postUrl, fieldName, files)
  var formData = new FormData();
  formData.append(fieldName, files);

  var req = new XMLHttpRequest();"POST", postUrl);
  req.onload = function(event) { console.log(; };
function onchange() {
  for (let i = 0; i < this.files.length; i++) {
    upload('/uploads', 'uploadfile', this.files[i]);
window.onload = function () {
var  input = document.getElementById('file');
input.addEventListener('change', onchange);
<input type="file" id="file" name="file" multiple onchange="upload" />

Server Codes

var express = require('express')
var app = express()
var path = require('path')
var tmpdir = require('os').tmpdir
var upload = require('multer')({dest: tmpdir()})

app.get('/', function (req, res) {
  var indexhtml = 'index.html';
  var tmp = path.resolve(indexhtml);
})'/uploads', upload.single('uploadfile'), function (req, res, next) {
  var rp = {'file':req.file, 'body' : req.body, 'ip':req.ip};


Run express Server

node index.js



As you can see in the console, the file was uploaded to server and saved with file name of "/tmp/e2f2d3ae260814fc4b589a13d5981aec".

Subscribe to Post, Code and Quiet Time.

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.