How To Handle Multipart Form Data in Nodejs ? File Uploading in Nodejs


Source

As a programmer very often you need to handle large amount of data to send using http based web services, and you must have experienced this sceanario as a developer where you must have used multipart/form-data to transact data between front-end & backend (servers). Today we will understans how to handle multipart/form-data in Node.js

Node multipart/form-data Explained :

Before we went on to uncover multipart/form data we need to understand what are the content-type 

Encoding Content Type :

You as a developer would have come across this two mechanism:

1.application/x-www-form-urlencoding

2.multipart/form-data

This encoding content-type are typically added to the enctype property on a FORM HTML element. application/x-www-form-urlencoded is mostly employed to submit standard form field as shown in code snippet 1 below :

// code snippet 1:
<form action="/update" method="post">  
  <input type="text" name="uname" />
  <button type="submit" />
</form>

And we very often switch to multipart/form-data where there is a need to upload a file to the server as shown in code snippet 2 below :

// code snippet 2: 
<form action="/update" method="post" encrypt="multipart/form-data>  
  <input type="text" name="uname" />
  <input type="file" name="mobibit" />
  <button type="submit" />
</form>

We will go staright to understand how to encode with multipart/form-data 

Encoding with form-data :

W3C says :

The content type “application/x-www-form-urlencoded” is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type “multipart/form-data” should be used for submitting forms that contain files, non-ASCII data, and binary data.

NPM gives us an easy way to manage multipart/form-data through a library to create readable "multipart/form-data" streams.

Refer this link here & install as shown below:

npm install --save form-data

Let’s See How To Use form-data library :

This example has been sourced from npjms.com here we will be creating a form containing three string as shown below

//code snippet 3
var FormData = require('form-data');
var fs = require('fs');
var form = new FormData();
form.append('u_field', 'my value');
form.append('u_data', new Buffer(10));
form.append('u_file', fs.createReadStream('/foo/bar.jpg'));

Also we can employ http-response stream as shown in code snippet 4

//code snippet 4
var FormData = require('form-data');
var http = require('http');

var form = new FormData();

http.request('http://nodejs.org/images/logo.png', function(response) {
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_logo', response);
});

also we can use request library stream as shown in code snippet 5 below :

//code snippet 5
var FormData = require('form-data');
var request = require('request');

var form = new FormData();

form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_logo', request('http://nodejs.org/images/logo.png'));

In order to submit this form to a web application, call submit(url, [callback]) method:

form.submit('http://example.org/', function(err, res) {
// res – response object (http.IncomingMessage)  //
res.resume();
});


There are other advanced mechanism to submit form in Nodejs but we will cover how to to do this using request :

Form submission using request:

See the code snippet below :

var formData = {
my_field: 'my_value',
my_file: fs.createReadStream(__dirname + '/img1.jpg'),
};

request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful!  Server responded with:', body);
});


For more details see request readme.

Some other articles on Nodejs which is recommended to better grab Nodejs :

1. Node.Js Vs PHP : Battle of Supremacy & survival

2. Getting Started With Nodejs

3. All About Node.Js You Wanted To Know ?

 References:

  1. https://github.com/request/request#multipartform-data-multipart-form-uploads
  2. https://www.npmjs.com/package/form-data
  3. http://derpturkey.com/node-multipart-form-data-explained/
  4. https://github.com/pillarjs/multiparty
  5. https://docs.nodejitsu.com/articles/HTTP/servers/how-to-handle-multipart-form-data/

Summary :

Handling multipart/form-data for file uploading is quite a complex process but Node leverages us developers with lots of third party packages & libraraies to make our life easy. Now you don’t need to worry about streaming binary data, writing streams to file, parsing form data and other complex procedures simply install npm libraries for form-data or use node-formidable by Felix Geisendorfer & handle, parsing forms and receiving file uploads in no time.

Be a smart programmer & also make your fellow developers smart by contributing to the active open source Nodejs community. We often get a lot, then expected when we collaborate & exchange.

Signing off with some data to consume about Javascript : brought to you by codeconquest.com

Pramod Chandrayan

Founder & CEO (Mobibit Soft (P) Ltd) | Mobile App Development Consultant | Startup Mentor | Spiritual Seeker

More Posts - Website

Follow Me:
TwitterFacebookLinkedInGoogle Plus

Related posts

Leave a Comment