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".

1 comment:

  1. For many web applications that let users share papers, photos, and other types of material, file uploads are a necessary functionality. Multer is a well-liked middleware used for Handling file uploads in Node.js using Multer middleware.in the Node.js environment to effectively handle file uploads. We’ll look at how to use Multer to create file uploads in Node.js in this in-depth tutorial, which covers everything like Multer typescript, Multer javascript from set up to save the configuration, and how to use Multer in node js, Multer GitHub and Step-by-step guide for file uploads with Multer in Node.js and how to implement file uploads in node.js using Multer?

    ReplyDelete

fixed: embedded-redis: Unable to run on macOS Sonoma

Issue you might see below error while trying to run embedded-redis for your testing on your macOS after you upgrade to Sonoma. java.la...