'How to return id of uploaded file (upload with multer in nodejs express app)
I have an MEAN stack app and trying to upload file with multer. Upload is working fine the only problem is I want to return uploaded file's id.
//multer settings for single upload
var upload = multer({ storage: storage }).single('file');
app.post('/upload', upload, function (req, res) {
//// ????? What to return and how?
});
I'm subscribed to this post into angular2 service. Thank you for help.
Solution 1:[1]
var multer = require('multer');
// storage for upload file.
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './file');
},
filename: function (req, file, callback) {
callback(null, file.originalname);
}
});
var Upload = multer({
storage: storage
}).any('file');
router.post('/upload', postData);
function postData(req, res) {
Upload(req, res, function (error) {
if (error) {
res.status(400).send(error);
}
var obj = {};
obj.file = req.files.filename;
//file is getting stored into database and after it successfully stored
//into database it will return you Id
db.create(obj, function (err, data) {
if (err) {
res.send('error');
}
if (!data) {
res.send('Error');
} else {
console.log('file upload');
res.send(data._id);
}
});
});
}
to return Id you should have to store reference somewhere in database and after that you will return id to Angular2
Solution 2:[2]
If you are using Mongo DB (GridFs-stream) to store the file the res object of the upload function has the object under res.req.file
which has all the details with the metadata and grid details of the uploaded file as below:
{
fieldname:'file',
originalname:'Screenshot (1).png',
encoding:'7bit',
mimetype:'image/png',
filename:'file-1516342158216.png',
metadata:{
originalname:'Screenshot (1).png',
email:'[email protected]',
imageType:'ProfilePic'
},
id:5 a618b8e1d9af11f388dcabb,
grid:{
_id:5 a618b8e1d9af11f388dcabb,
filename:'file-1516342158216.png',
contentType:'image/png',
length:675410,
chunkSize:261120,
uploadDate:2018-01 -19 T06:09:18.736 Z,
aliases:undefined,
metadata:{
originalname:'Screenshot (1).png',
email:'[email protected]',
imageType:'ProfilePic'
},
md5:'fdda12a2f098a915c24162dc410cb3b6'
},
size:undefined
}
Solution 3:[3]
The request file object (req.file) doesn't contain any unique ID, you will have to roll your own ID assigning logic.
You will have to think for what purpose you need that ID, then you can use information stored in the request file object (req.file
) to make it specific for that file.
For example, if all the files are stored in the same path, and the ID will be used to retrieve that file later on, then you have to think in a strategy that wont give you problems with user input.
Each file uploaded with multer
contains the following information:
**:Key:** **:Description:**
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
destination The folder to which the file has been saved (DiskStorage only)
filename The name of the file within the destination (DiskStorage only)
path The full path to the uploaded file (DiskStorage only)
buffer A Buffer of the entire file (MemoryStorage only)
So you can use the file name (used in the form) req.file.fieldname
.
Or the original file req.file.originalname
(but using originalname
only can create problems if you upload the same filename multipletime, so...)
Even better, create a unique string for the file by combining a current date timestamp with the filename/original
like : timestamp-filename.ext
Or generate a random hash (example using the string timestamp-filename.ext
)
5910c2f5df0471320b8fc179fa6dc1114c1425752b04127644617a26a373694a
(SHA256)
Solution 4:[4]
var multer = require('multer');
var MongoClient = require('mongodb').MongoClient;
// storage for upload file.
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './file'); //here you can pass your file path
},
filename: function(req, file, callback) {
callback(null, file.originalname);
//var name=file.originalname
//callback(null,name)
}
});
var Upload = multer({
storage: storage
}).any('file');
router.post('/upload', postData(req, res) {
Upload(req, res, function (error) {
if (error) {
res.status(400).send(error);
}
});
//here you pass your connection of mongodb link and you have to also create a
//db file aslo other wise it will show error
var obj = {};
obj.file = req.files.filename;
//file is getting stored into database and after it successfully stored
//into database it will return you Id
db.create(obj, function(err, data) {
if (err) {
res.send('error');
}
if (!data) {
res.send('Error');
} else {
console.log('file upload');
res.json(data._id);
}
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Santosh Suryawanshi |
Solution 2 | clemens |
Solution 3 | EMX |
Solution 4 | Tyler2P |