68468

How to return id of uploaded file (upload with multer in nodejs express app)

Question:

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.

Answer1:

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

Answer2:

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.

<hr />

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)

Answer3:

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:'prasan.g8@gmail.com', 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:'prasan.g8@gmail.com', imageType:'ProfilePic' }, md5:'fdda12a2f098a915c24162dc410cb3b6' }, size:undefined }

Recommend

  • Linq distinct based on two columns
  • Android CalendarContract, deleting a recurring event causes all events to disappear on calendar?
  • FindAndModify, return array of Objects
  • Mongodb exception, “ MongoCursorException' with message '$ operator made object too large”
  • How to load gif image while ajax content is loading and javascript [duplicate]
  • Open Existing DB in MySQL WorkBench
  • D3 get axis values on zoom event
  • Using a canvas object in a thread to do simple animations - Java
  • Detect when Facebook like button is clicked
  • How can I extract results of aggregate queries in slick?
  • MonoTouch: How to download pdf incrementally as indicated in the Apple slides “Building Newsstand Ap
  • Needing to do .toArray() to get output of mongodb .find() on key name not value
  • Make VS2015 use angular-cli ng at build time in a .NET project
  • MongoError: Incorrect arguments
  • MongoDB in PHP using aggregate to group by _id is null not working
  • Obtain ObjectIdHex value from mgo query
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Upload files with Ajax and Jquery
  • How to pass list parameters for each object using Spring MVC?
  • SVN: Merging two branches together
  • jqPlot EnhancedLegendRenderer plugin does not toggle series for Pie charts
  • How do I rollback to a specific git commit
  • Is there a mandatory requirement to switch app.yaml?
  • Comma separated Values
  • AngularJs get employee from factory
  • Proper way to use connect-multiparty with express.js?
  • Error creating VM instance in Google Compute Engine
  • Hits per day in Google Big Query
  • how does django model after text[] in postgresql [duplicate]
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • embed rChart in Markdown
  • Turn off referential integrity in Derby? is it possible?
  • LevelDB C iterator
  • Linking SubReports Without LinkChild/LinkMaster
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • Busy indicator not showing up in wpf window [duplicate]
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • Binding checkboxes to object values in AngularJs
  • How can I use `wmic` in a Windows PE script?
  • Unable to use reactive element in my shiny app