NodeJS-使用带有承诺的Multer上传

最近我一直在重写非常简单的服务器。我一直在介绍Promise,并且重写的最后一部分是实现我的发布方法,其中涉及使用Multer上传图像。 到目前为止,这就是我所拥有的。 GET完美,就像我删除图片上传部分时的POST一样。 不幸的是,当我介绍Multer时,会出现此错误:

TypeError: Cannot convert object to primitive value
   at exports.format (util.js:91:18)
   at Console.log (console.js:46:37)
   at Object.createACategory (/root/api/controllers/controller.js:34:18)

这是我的Route类,我在其中调用POST:

'use strict';
module.exports = function(app,gameCategoryList) {
  var multer = require('multer');

  var storage =   multer.diskStorage({
    destination: function (req,file,callback) {
      callback(null,'/var/www/html/uploadsCategoryIcon');
    },filename: function (req,callback) {
      var originalname = file.originalname;
      var extension = originalname.split(".");
      callback(null,extension[0] + '-' + Date.now() + '.' + extension[extension.length-1]);
    }
  });

  var upload = multer({ storage: storage });

  app.get('/api/gameCategories',(req,res) => {
    gameCategoryList.listAllCategories().then(category => res.json(category));
  });

  app.post('/api/createGameCategory',upload.single('gameCategoryImage'),res) => {
    gameCategoryList.createACategory(req.body,req.file).then(category => res.json(category));
  });

};

这是我的控制器类中的方法:

createACategory(body,file) {
         var splitPath = file.path.split("html");
         var imagePath = 'example.com' + splitPath[1];

         var new_category = new Category({
           categoryName: body.categoryName,categoryTag: body.categoryTag,categoryImageUrl: imagePath
         });

         return new Promise(function(resolve,reject) {

           new_category.save(function(err,category) {
             if (err) {
               return reject(err)
             } else {
               return resolve(category)
             }
           });

          }).then((category) => {

            if(category)
            {
              return category
            }
            else
            {
              return { success: false }
            }
          });
       }

更新:

controller.js的第34行是:

var new_category = new Category({
   categoryName: body.categoryName,categoryImageUrl: imagePath
});

当我删除此代码的图像部分(categoryImageUrl:imagePath)并且不传递任何文件或图像时,此代码可以正常工作。

slxxfl0000 回答:NodeJS-使用带有承诺的Multer上传

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3120128.html

大家都在问