How to upload file by using request module

request
module
node js

In request module we are sending files by using below code. The syntax for installing request module is

npm install request --save

Include this module by using below syntax.

var request = require('request');

the syntax for request module to send files

try{
	var fname = 'sample.pdf';
	var options = {
		method: 'POST',
		url: 'URL',
		headers:{
			'postman-token': '8252bb2f-6b2a-657b-b43c-6054fc47c84e',
			'cache-control': 'no-cache',
			'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' 
		},
		formData:{
			File-Name: 'sample',
			File:{
				value : fs.createReadStream(fname),
				options : { filename: fname, contentType: null } 
			}
		}
	};
	
	request(options, function (error, response, body) {
		if (!error && response.statusCode == 201) {
			var responses = JSON.parse(response.body);
		}else{
			console.log('Error File Uploading');
			console.log(error);	
		}
	});
}
catch(e){
    console.log(e);
}

 

You might also like:

Compare the Triplets | Javascript | hackerrank.com

07-05-2020 hackerrank.com

Check null values in JavaScript?

04-02-2019 JavaScript null check null value

Convert and download html to pdf without saving file

28-10-2018 node js convert html to pdf pdf download pdf without saving

Get previous date from given date in javascript

06-03-2017 date javascript previous date

Filter for insert HTML in Angular Js

06-03-2017 filter show html angular js html