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

耗尽温柔 提交于 2019-12-12 04:07:42

问题


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.


回答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




回答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:'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
}



回答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)



来源:https://stackoverflow.com/questions/45889947/how-to-return-id-of-uploaded-file-upload-with-multer-in-nodejs-express-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!