node.js : file upload via express and multer

Form-based File Upload in HTML

https://tools.ietf.org/html/rfc1867

Express

Fast, unopinionated, minimalist web framework for node.

Multer

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();
  req.open("POST", postUrl);
  req.onload = function(event) { console.log(event.target.responseText); };
  req.send(formData);
}
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);
}
</script>
<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);
  res.sendFile(tmp);
})

app.post('/uploads', upload.single('uploadfile'), function (req, res, next) {
  var rp = {'file':req.file, 'body' : req.body, 'ip':req.ip};
  res.send(rp);
})

app.listen(3000)

Run express Server

node index.js

Test

upload

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.
jamie@example.com
Subscribe