I am now using Express4 and want to upload files to the file system of the server. (for example, save the files in the public/files
folder.)
There are several questions about how to user formidable
or busboy
to parse the request like this example:
var formidable = require('formidable'),
http = require('http'),
util = require('util');
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'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
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);
Such middleware could parse req
to get the metadata, like the file path, name, size, etc. However, if I want to POST different files to different endpoints, I would like to use angularjs controller and service structure to process the uploading.
Wondering how can I get file path, name, etc to controller/service and post them to the backend. Then I can use the following codes to upload files.
api.post(url, function(req, res) {
var fs = require('fs');
//req.body.path: path of file, like, C:\\user\John\.....
//req.body.filename: name of file, like images.jpg
fs.readFile(req.body.path, function(err, data){
var uploadToPath = './public/files/' + req.body.filename;
fs.writeFile(uploadToPath, data, function(err){
if(err) {
res.send(err);
return;
}
});
});
});
I am also referring this solution, but it can only get the info like file size, but not the very important file path.
pls advise, many thanks.
For the node/express side:
Check out https://github.com/expressjs/multer
For the angular side:
Check out https://github.com/danialfarid/ng-file-upload
It makes uploading and saving single or multiple files super easy. They have an option in there for directory to automatically save to.