I am using the following to upload files to a directory via Multer. It works great, but I need to perform some actions after upload that require the name of the file I just posted to the "upload" directory. How do I get the name of the file I just posted?
// Multer storage options
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'upload/');
},
filename: function(req, file, cb) {
cb(null, file.originalname + '-' + Date.now() + '.pdf');
}
});
var upload = multer({ storage: storage });
app.post('/multer', upload.single('file'), function(req, res) {
// Need full filename created here
});
var express=require("express");
var app=express();
var multer=require("multer");
var upload=multer({dest:"uploads/"});
app.post("/multer", upload.single("file"), function(req,res){
console.log(req.file.filename);
});
request.file gives the following stats, from which you would just need to pick request.file.originalname or request.file.filename to get the new filename created by nodejs app.
{
fieldname: 'songUpload',
originalname: '04. Stairway To Heaven - Led Zeppelin.mp3',
encoding: '7bit',
mimetype: 'audio/mp3',
destination: './uploads',
filename: 'songUpload-1476677312011',
path: 'uploads/songUpload-1476677312011',
size: 14058414
}
Eg, in nodejs express mvc app with ecma-6,
var Express = require('express');
var app = Express();
var multipartUpload = Multer({storage: Multer.diskStorage({
destination: function (req, file, callback) { callback(null, './uploads');},
filename: function (req, file, callback) { callback(null, file.fieldname + '-' + Date.now());}})
}).single('songUpload');
app.post('/artists', multipartUpload, (req, resp) => {
val originalFileName = req.file.originalname
console.log(originalFileName)
}
Accessing uploaded files data differs in Multer, depending whether you are uploading single or multiple files. Access data like so:
uploading single file:
req.file
uploading multiple files:
req.files
I found the answer on github, you have access to it in
res.req.file.filename
See there for more informations https://github.com/expressjs/multer/issues/302
app.post('/multer', upload.single('file'), function(req, res) {
// Need full filename created here
const file = req.file
if (!file) {
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
res.send(file) #Here
});
You need recover file from this line
res.send(file)
using file.filename
This output sample
{
"fieldname": "myFile",
"originalname": "isc te esta esperando.jpg",
"encoding": "7bit",
"mimetype": "image/jpeg",
"destination": "uploads",
"filename": "myFile-1602293858948.eaf",
"path": "uploads/myFile-1602293858948.eaf",
"size": 297720
}
using
request.file.filename
fieldname Field name specified in the form
originalname Name of the file on the user's computer
encoding Encoding type of the file
mimetype Mime type of the file
size Size of the file in bytes
Related
I'm using Multer to upload and store files. If I use the dest option files upload to my /uploads folder with no problem. Whilst this works, it's saving the uploads like 2eb3f1a6def453f7a461c5de353b06f8 so I want to use the storage option, but for some reason this doesn't work or me and the files upload (logged in console), but wont save to the folder.
I've tried a few different ways of achieving this and none work. Can anyone point out what might be wrong?
{
fieldname: 'attachments',
originalname: 'myFile.pdf',
encoding: '7bit',
mimetype: 'application/pdf',
destination: 'uploads/',
filename: '2eb3f1a6def453f7a461c5de353b06f8',
path: 'uploads/2eb3f1a6def453f7a461c5de353b06f8',
size: 57638
}
const express = require('express');
const app = express();
const multer = require("multer");
const path = require('path');
// const upload = multer({ dest: "uploads/" }); // this works, file saves to /uploads
var upload = multer({ storage: storage }); // this doesnt work/ files dont save to /uploads
// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded());
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
var storage = multer.diskStorage({
destination: function(req, file, cb) {
// cb(null, 'uploads/');
// cb(null, __dirname + '/uploads');
cb(null, './uploads');
},
filename: function (req, file, cb) {
// cb(null , file.originalname);
// cb(null, file.fieldname + '-' + Date.now());
// By default, multer removes file extensions so let's add them back
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
// var upload = multer({ storage: storage });
app.post('/', upload.array('attachments') , (req, res) =>{
try {
res.send(req.files);
console.log('body', req.body);
console.log('files', req.files);
} catch(error) {
console.log(error);
res.send(400);
}
});
module.exports = {
path: '/api/upload',
handler: app
};
Declaring var upload = multer({ storage: storage }) after having it defined with multer.diskStorage was enough to fix OP's issue.
I'm using multer as express middleware to upload a file like so:
const upload = multer().single('fieldName');
router.post(
'/',
upload,
(req, res) => {
console.log(req.file)
}
);
It works fine except when I sent the form without a file. Then apparently the upload middleware is just skipped and req.file is undefined.
I tried to add a filter like so but apparently the filter function is not called when there is no file:
function fileFilter(req, file, cb) {
console.log('filtering'); //never reached when file is missing
if (!file) {
return cb(new Error('no file', false));
}
cb(null, true);
}
const upload = multer({fileFilter: fileFilter}).single('fieldName');
router.post(...)
Is there any way to handle the missing file inside the multer middleware? Or do I have to check afterwards?
check in you html form "fieldName" in input name
and this can you help
in you routes app
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now()+'.mp3')
}
})
var upload = multer({ storage: storage })
router.post(
'/uploadfile',upload.single('fieldName'),
)
I am trying to upload an image using express but I am facing two problems, first, whenever I upload the same image again it's not getting uploaded and secondly after uploading any single image a file with image also uploading. Here is my code.
var multer = require('multer');
var uploads = multer({dest: './images'});
app.post('/uploading', uploads.single("file"), function (req, res) {
var file = __dirname +"/images" + "/" + req.file.originalname;
fs.readFile( req.file.path, function (err, data) {
fs.writeFile(file, data, function (err,data) {
if( err ){
console.error( err );
response = {
message: 'Sorry, file couldn\'t be uploaded.',
filename: req.file.originalname
};
}else{
response = {
message: 'File uploaded successfully',
filename: req.file.originalname
};
}
res.end( JSON.stringify( response ) );
});
});
})
The uploads.single("file") middleware Will handle the file upload. You don't have to specifically fs.read and fs.write the file.
var multer = require('multer');
var uploads = multer({dest: './images'});
app.post('/uploading', uploads.single("file"), function (req, res) {
//the file is uploaded automatically
})
EDIT: The above code will upload the file with hex string as filename without any extension.
In order to add rename function you need to use diskStorage. Here is the code taken from this github issue page.
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './images/')
},
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
cb(null, raw.toString('hex') + Date.now() + '.' + mime.extension(file.mimetype)); //this is the rename func
});
}
});
var uploads = multer({ storage: storage });
app.post('/uploading', uploads.single("file"), function (req, res) {
//the file is uploaded automatically
})
Now you can use the uploads variable as middleware as shown in the above snippet.
you can edit the filename: function (req, file, cb) { .. } according to your needs. Now the filename will be, <16characterhexstring>.ext
another way to handle it will be not using middleware and using multer manually with below options :
try {
var storage = multer.diskStorage({
destination: function(request, file, callback) {
//define folder here by fs.mkdirSync(anyDirName);
},
filename: function(req, file, callback) {
callback(null, anyFileName);
},
limits: self.limits
});
var upload = multer({
storage: storage,
fileFilter: function(request, file, callback) {
// here you can filter out what not to upload..
}
}).any();
upload(request, response, callback);
} catch (e) {
}
hope this helps!
I have uploaded files of different types(image, pptx, video and docx) using Multer in the folder named 'uploads'.
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.originalname);
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
/** API path that will upload the files */
app.post('/upload', function(req, res) {
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}
res.json({error_code:0,err_desc:null});
});
});
Now the uploaded files are being stored in 'uploads' folder like /uploads/demo.pptx
I need to fetch these and send the filepath or url of the stored files and send as a response to client so they can access to watch or download it.
Usually, files stored in DB when you need to do more than just serve them and upload new files. For this proposes, you could save only file's metadata to DB(such as size, type, path, name). However if you for some reason still need to store files in DB, MongoDB have GridFS component and provides a documentation about working with this component.
you can do something like this:-
var mongojs = require('mongojs');
var db = mongojs(//credential here);
var uploaded_file=db.collection("uploaded_file");
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.originalname);
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
/** API path that will upload the files */
app.post('/upload', function(req, res) {
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}else{
uploaded_file.insert(res.file,function(err, saved) {// i am asuming res.file have the information you needed to send
if(err){
console.log("Unexpected error occurred during insertion in database:"+err);
}else{
res.send({error_code:0,file_info:res.file});
res.end();
}
});
}
});
});
I'm using "multer": "^1.0.6", And i Want to save image in upload folder.
My code is
app.post('/post', multer({dest: './uploads/'}).single('file'), function (req, res) {
response = {
message: 'File uploaded successfully',
filename: req.file.filename
};
res.end(JSON.stringify(response));
});
But I Have the file with this name in upload folder 8e6e425f8756e0bafb40ed1a3cb86964
Why I have this name without mimetype?
Multer saves files without extensions you can read this on GitHub:
filename is used to determine what the file should be named inside the folder. If no filename is given, each file will be given a random name that doesn't include any file extension.
If you want to save with the extension that you write your code like here:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
cb(null, file.originalname); // modified here or user file.mimetype
}
})
var upload = multer({ storage: storage })
All information you can find here https://github.com/expressjs/multer/blob/master/README.md
Multer not worried about the extension of the file and leave it completely on your side: you have to define itself a function that will do it. For example, like this:
var multer = require('multer');
var upload = multer({ storage: multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
var ext = require('path').extname(file.originalname);
ext = ext.length>1 ? ext : "." + require('mime').extension(file.mimetype);
require('crypto').pseudoRandomBytes(16, function (err, raw) {
cb(null, (err ? undefined : raw.toString('hex') ) + ext);
});
}
})});
app.post('/post', upload.single('file'), function (req, res) {
response = {
message: 'File uploaded successfully',
filename: req.file.filename
};
res.end(JSON.stringify(response));
});