I'd like to change the file name to other that's send as a property of the data object, here's the json of the file:
{ fieldname: 'file',
originalname: 'db.pdf',
encoding: '7bit',
mimetype: 'application/pdf',
destination: './client/public/docs/transactions/',
filename: '8a3fe7cb7369d9cffa8e17b162ec3d6b',
path: 'client\\public\\docs\\transactions\\8a3fe7cb7369d9cffa8e17b162ec3d6b',
size: 9179145 }
Client side upload with ng-file-upload:
Upload
.upload( {
url: '/api/v1/upload',
data: {
file: vm.pdf,
new_name: vm.new_pdf_name //This is the name I want for the file
}
} )
.then(
function ( response ) { ... }
);
I'm using diskStorage but the request of filename property function doesn't receive new_file_name property...
var storage = multer.diskStorage(
{
destination: './uploads/',
filename: function ( req, file, cb ) {
//req.body is empty...
cb( null, file.originalname );
}
}
);
How could I send the new_file_name through that req.body?
If req.body is empty, it means that the client sent the file before sending the new_file_name field. There is nothing we can do about it in multer.
This has come up a number of times before, e.g. #146 where the workaround is further outlined.
Emmm, acually req.body at the endpoint contains it, but the req.body I mean is this:
var storage = multer.diskStorage(
{
destination: './uploads/',
filename: function ( req, file, cb ) {
//req.body is empty... here is where req.body.new_file_name doesn't exists
cb( null, file.originalname );
}
}
);
But in this req.body it exists:
var upload = multer( { storage: storage } );
router.route( '/upload' )
.post( upload.single( 'file' ), function ( req, res ) {
console.log( req.body.new_file_name );
//Prints the value sent from the client...
res.json({message:'File Uploaded!'});
} );
Yes that is the expected behaviour, the filename function is called whenever a file is detected on the wire. It needs to run before the file is actually consumed since it determines where to save it.
Your request from the client looks like this:
<header> | file | new_file_name
^ filename function fired
You need to send it as such:
<header> | new_file_name | file
^ filename function fired
I don't really understand what you're trying to tell me... I only need to know how to get the new_file_name value at:
filename: function ( req, file, cb ) {
cb( null, req.body.new_file_name );
}
I understand, but at that point in time the information about new_file_name haven't arrived at the server yet.
Then how could I set a custom name to the file sent from the client?
Take a look on #170 . I prefer the way with the mime module.
https://github.com/expressjs/multer/issues/170#issuecomment-123362345
Most helpful comment
Yes that is the expected behaviour, the
filenamefunction is called whenever a file is detected on the wire. It needs to run before the file is actually consumed since it determines where to save it.Your request from the client looks like this:
You need to send it as such: