【问题标题】:How to return id of uploaded file (upload with multer in nodejs express app)如何返回上传文件的 id(在 nodejs express 应用中使用 multer 上传)
【发布时间】:2022-04-16 17:59:55
【问题描述】:

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

我已将这篇文章订阅到 angular2 服务中。 谢谢你的帮助。

【问题讨论】:

  • @rckrd 它也是这样工作的,我将它作为第二个参数传递给帖子。
  • 但无论如何,如果我在帖子中这样调用它: app.post('/upload', function (req, res) { upload(req, res, function (err) { if (err ) { res.json({ error_code: 1, err_desc: err }); return; } console.log(res); }); });在控制台中,我看到还包含文件对象的大对象,它有 id 这就是我想要发回的内容

标签: node.js express multer


【解决方案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);
                        }
                    });
            });
       }

要返回 ID,您必须将引用存储在数据库中的某处,然后您将返回 id 到 Angular2

【讨论】:

    【解决方案2】:

    如果您使用 Mongo DB (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
    }
    

    【讨论】:

      【解决方案3】:

      请求文件对象 (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)

      【讨论】:

      • 在上传函数的res中存在id,我在DB表中也看到了这个id..问题是我无法返回它。
      【解决方案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);
              }
          });
      });
      

      【讨论】:

      • 您的答案可以通过添加有关代码的作用以及它如何帮助 OP 的更多信息来改进。
      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2018-07-21
      • 2017-10-28
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      • 2016-10-22
      • 2018-06-14
      • 2020-05-21
      • 1970-01-01
      相关资源
      最近更新 更多