Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when using mv module to rename a file with buffer data

I am using mv module for express js, and i am having an issue with saving my uploaded file to a certain directory of my choosing.

when i access my file data i have this info:

fieldname : 'file',
originalname : ....,
encoding :7bit,
mimetype 'image/jpeg',
buffer : <Buffer ff d8 ff e1 ...>

when i use mv to do the following:

   mv( req.file.buffer , path.normalize(__dirname+'/public/uploads/'+ p._id +'.jpg'), {mkdirp: true} ,function(err){
            if(err) console.log(err);
            res.json({});
        });

I see an error saying:

"Path must be a string without null bytes."

What am i doing wrong? how can i fix it?

like image 377
Royz Avatar asked Feb 01 '26 05:02

Royz


1 Answers

var fs = require('fs');
var OS = require('os');
var path = require('path');

var tmpPath = path.join(OS.tmpdir(), Date.now());

//saving file to tmp dir with random name
fs.writeFile(tmpPath, req.file.buffer, function(err) {
  if (err) {
    return res.error(err);
  }
  //moving file somewhere else
  mv(tmpPath, path.normalize(__dirname+'/public/uploads/'+ p._id +'.jpg'), {mkdirp: true} ,function(err){
        if(err) console.log(err);
        res.json({});
    });
})
like image 108
Nazar Sakharenko Avatar answered Feb 03 '26 00:02

Nazar Sakharenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!