//<html>
//<head><title> NodeJS File Upload Example </title></head>
//<body>
//<form action="http://localhost:80/upload" method="post" enctype="multipart/form-data">
// <input type="file" name="fileupload">
//<br>
//<input type="submit">
//</form>
//</body>
//</html>
let http = require('http');
let formidable = require('formidable');
let fs = require('fs');
http.createServer(function (req, res) {
//Create an instance of the form object
let form = new formidable.IncomingForm();
//Process the file upload in Node
form.parse(req, function (error, fields, file) {
let filepath = file.fileupload.filepath;
let newpath = 'C:/upload-example/';
newpath += file.fileupload.originalFilename;
//Copy the uploaded file to a custom folder
fs.rename(filepath, newpath, function () {
//Send a NodeJS file upload confirmation message
res.write('NodeJS File Upload Success!');
res.end();
});
});
}).listen(80);
router.post('/upload', function(req, res) {
let valid_response = {
status: true
};
if (!req.files || Object.keys(req.files).length === 0) {
valid_response['status'] = false;
valid_response['message'] = 'No files were uploaded.';
return res.status(400).send(valid_response);
}
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
let sampleFile = req.files.file;
// Use the mv() method to place the file somewhere on your server
sampleFile.mv(__dirname + '/../media/' + sampleFile.name, function(err) {
if (err)
return res.status(500).send(err);
valid_response['file'] = sampleFile.name;
valid_response['file_type'] = sampleFile.mimetype;
return res.send(valid_response);
});
});