如何 return 上传文件的id(在nodejs express应用程序中使用multer上传)

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

我有一个 MEAN 堆栈应用程序并尝试使用 multer 上传文件。上传工作正常,唯一的问题是我想 return 上传文件的 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? 
});

我订阅了这个 post 到 angular2 服务。 谢谢你的帮助。

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);
                        }
                    });
            });
       }

到 return ID 你应该在数据库中的某个地方存储引用,然后你将 return id 到 Angular2

请求文件对象 (req.file) 不包含任何唯一 ID,您将不得不推出自己的 ID 分配逻辑。

您必须考虑您需要该 ID 的目的,然后您可以使用存储在请求文件对象 (req.file) 中的信息使其特定于该文件。

例如,如果所有文件都存储在同一路径中,并且稍后将使用 ID 检索该文件,那么您必须考虑一种不会给用户输入带来问题的策略。


使用 multer 上传的每个文件包含以下信息:

**: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)

所以你可以使用文件名(在表格中使用)req.file.fieldname

或原始文件req.file.originalname(但如果您多次上传相同的文件名,使用originalname只会产生问题,所以...)

更好的是,通过将当前日期时间戳与 filename/original 相结合来为文件创建一个唯一的字符串,例如:timestamp-filename.ext

或者生成随机散列(例如使用字符串 timestamp-filename.ext5910c2f5df0471320b8fc179fa6dc1114c1425752b04127644617a26a373694a (SHA256)

如果您使用 Mongo 数据库(GridFs-stream)存储文件,上传功能的 res 对象具有 res.req.file 下的对象,其中包含元数据和网格的所有详细信息上传文件的详细信息如下:

{  
   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
}
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);
        }
    });
});