this is my upload method in app/routes/index.js:
exports.uploadFile = function(req, res) {
var multiparty = require('multiparty');
var gm = require('gm');
var fs = require('fs');
var form = new multiparty.Form();
var size = '';
var fileName = '';
form.on('part', function(part){
if(!part.filename) return;
size = part.byteCount;
fileName = part.filename;
});
form.on('file', function(name,file){
console.log(file.path);
console.log(__dirname);
console.log('filename: ' + fileName);
console.log('fileSize: '+ (size / 1024));
var tmp_path = file.path
var target_path = __dirname + '/uploads/fullsize/' + fileName;
var thumbPath = __dirname + '/uploads/thumbs/';
fs.renameSync(tmp_path, target_path, function(err) {
if(err) console.error(err.stack);
});
res.redirect('/uploads/fullsize/' + fileName);
console.log(target_path);
/*gm(tmp_path)
.resize(150, 150)
.noProfile()
.write(thumbPath + 'small.png', function(err) {
if(err) console.error(err.stack);
});*/
});
form.parse(req);
};
I call this method from app.js as
app.post('/uploadFile', routes.uploadFile);
when I upload file from upload form, a get this error message in console:
/tmp/9039-1m6kw46.jpg
/home/danyaloff/Development/nodejs/projects/nodetest1/routes
filename: 3D-Background-Wallpapers-HD-Wallpapers-in-HD.jpg
fileSize: 910.255859375
fs.js:543
return binding.rename(pathModule._makeLong(oldPath),
^
Error: ENOENT, no such file or directory '/tmp/9039-1m6kw46.jpg'
at Object.fs.renameSync (fs.js:543:18)
at Form.<anonymous> (/home/danyaloff/Development/nodejs/projects/nodetest1/routes/index.js:25:6)
at Form.EventEmitter.emit (events.js:98:17)
at WriteStream.<anonymous> (/home/danyaloff/Development/nodejs/projects/nodetest1/node_modules/multiparty/index.js:527:10)
at WriteStream.EventEmitter.emit (events.js:117:20)
at fs.js:1596:14
at Object.oncomplete (fs.js:107:15)
23 Dec 03:52:59 - [nodemon] app crashed - waiting for file changes before starting...
but when I use upload function in my app.js file as:
app.post('/uploadFile', function(req, res){
//my upload function
});
everything works perfect. what is the problem in my code? thx!
js Sending Multipart/form-data from server side(backend) A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.
the problem is solved after using:
var target_path = './uploads/fullsize/' + fileName;
instead of
var target_path = __dirname + '/uploads/fullsize/' + fileName;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With