Reputation: 634
I am new to nodeJS and Java Script. I need to implement a mechanism to read a file in nodeJS server sent from the Web Client.
Can anyone give me some pointer how to do that?
I found readFileSync()
in nodeJS filesystem which can read the contents of a file. But how to retrieve the file from the request sent by Web Browser? And if the file is very big, then what is the best way to read the contents in that file in nodeJS?
Upvotes: 5
Views: 7365
Reputation: 34072
formidable is a very handy library for working with forms.
The following code is a fully functional example node app which I took from formidable's github and slightly modified. It simply displays a form on GET, and handles the upload from the form on POST, reading the file and echoing its contents:
var formidable = require('formidable'),
http = require('http'),
util = require('util'),
fs = require('fs');
http.createServer(function(req, res) {
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// parse a file upload
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
// The next function call, and the require of 'fs' above, are the only
// changes I made from the sample code on the formidable github
//
// This simply reads the file from the tempfile path and echoes back
// the contents to the response.
fs.readFile(files.upload.path, function (err, data) {
res.end(data);
});
});
return;
}
// show a file upload form
res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
}).listen(8080);
This is obviously a very simple example, but formidable is great for working with large files too. It gives you access to a read stream of the parsed form data as it's handled. This allows you to work with the data as it's being uploaded, or pipe it directly into another stream.
// As opposed to above, where the form is parsed fully into files and fields,
// this is how you might handle form data yourself, while it's being parsed
form.onPart = function(part) {
part.addListener('data', function(data) {
// do something with data
});
}
form.parse();
Upvotes: 7
Reputation: 5144
You will need to parse the body of the http request which can contain a file from an HTML file input. For instance, when using the express web framework with node, you can send a POST request via an HTML form and access any file data via req.body.files. If you're just using node, have a look at the 'net' module to assist in parsing http requests.
Upvotes: 2