Created
June 18, 2020 16:29
-
-
Save srinivas69/08543a5b30b7f9918458cace706be2ad to your computer and use it in GitHub Desktop.
upload file nodejs api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require('path'); | |
const formidable = require('formidable'); | |
const fs = require('fs'); | |
//upload file api | |
app.post('/uploadfile',upload_file); | |
function upload_file(req, res, next){ | |
if(req.method == "POST") { | |
// create an incoming form object | |
var form = new formidable.IncomingForm(); | |
// specify that we want to allow the user to upload multiple files in a single request | |
form.multiples = true; | |
// store all uploads in the /uploads directory | |
form.uploadDir = path.basename(path.dirname('/uploads/json_files/')) | |
// every time a file has been uploaded successfully, | |
// rename it to it's orignal name | |
form.on('file', function(field, file) { | |
fs.rename(file.path, path.join(form.uploadDir, file.name), function(err){ | |
if (err) throw err; | |
//console.log('renamed complete: '+file.name); | |
const file_path = '/uploads/'+file.name | |
}); | |
}); | |
// log any errors that occur | |
form.on('error', function(err) { | |
console.log('An error has occured: \n' + err); | |
}); | |
// once all the files have been uploaded, send a response to the client | |
form.on('end', function() { | |
//res.end('success'); | |
res.statusMessage = "Process cashabck initiated"; | |
res.statusCode = 200; | |
res.redirect('/') | |
res.end() | |
}); | |
// parse the incoming request containing the form data | |
form.parse(req); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment