I'm receiving following files in the server
{"file":{"size":6818,"path":"/tmp/a451340156a9986cd9d208678bdc40cf","name":"test.pdf","type":"application/pdf","mtime":"2014-09-03T15:26:25.733Z"}}
I have file updload handing as follows:
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
console.log(JSON.stringify(files));
// `file` is the name of the <input> field of type `file`
var old_path = files.file.path,
file_size = files.file.size,
file_ext = files.file.name.split('.').pop(),
index = old_path.lastIndexOf('/') + 1,
file_name = old_path.substr(index),
new_path = path.join(process.env.PWD, '/uploads/', file_name + '.' + file_ext);
fs.readFile(old_path, function(err, data) {
fs.writeFile(new_path, data, function(err) {
fs.unlink(old_path, function(err) {
if (err) {
res.status(500);
res.json({'success': false});
} else {
res.status(200);
res.json({'success': true});
}
});
});
});
});
This gives 200 ok but file is not uploaded to desired directory i.e upload/
new_path is returned as /home/abc/myapp/uploads/0bc49fa19d15fb5bdf779c02d3cbc1d5.pdf
however it should just be /uploads/test.pdf
Is it the path or the filename that's causing the issue?
I'd start by simplifying the code by using the rename function. It would look something like this.
var newFilePath = path.join(process.env.PWD, 'uploads', files.file.name);
fs.rename(files.file.path,newFilePath,function(err){
if(err){
//handle error
}
res.json({success: 'true'});
});