为什么在Multer Node.js中req.files为空

时间:2018-07-13 06:49:14

标签: javascript node.js express multer

我认为multer无法从以下形式获得价值:

//Set Storage Engine
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + '.jpg')
  }
});
//upload var
var upload = multer({ storage: storage });

// route create
var cpUpload = upload.fields([{ name: 'image', maxCount: 0 }]);

app.post('/blog',cpUpload, multipartMiddleware,function (req, res,next) {

var image = req.files;
var newBlog = { image: image};
//store data 
  console.log("files", req.files);
  console.log("body", req.body);
          Blog.create(newBlog, function(err, newlyCreated){

    if ("error",err) {
      // An error occurred when uploading
      console.log(err);
    }
    res.redirect("/blog");
    })
    // Everything went fine
    //   });

  });

my form is :

          <form action="/blog" method="POST" enctype="multipart/form-data"> 

                <div class="form-group">
                    <input class="form-control" type="file" name='image' >  
                </div>

                <div class="form-group">
                    <button class="btn btn-lg btn-primary btn-block">Submit! 
                    </button>
                </div>
            </form>

结果显示:

files {}
body {}
{ ValidationError: Blog validation failed: image: Cast to String failed for value "{}" at path "image"
    at MongooseError.ValidationError (C:\Project\Image\node_modules\mongoose\lib\error\validation.js:27:11)
    at model.Document.invalidate (C:\Project\Image\node_modules\mongoose\lib\document.js:1861:32)
    at model.$set (C:\Project\Image\node_modules\mongoose\lib\document.js:874:10)
    at model._handleIndex (C:\Project\Image\node_modules\mongoose\lib\document.js:684:14)
    at model.$set (C:\Project\Image\node_modules\mongoose\lib\document.js:641:22)
    at model.Document (C:\Project\Image\node_modules\mongoose\lib\document.js:112:12)
    at model.Model (C:\Project\Image\node_modules\mongoose\lib\model.js:64:12)
    at new model (C:\Project\Image\node_modules\mongoose\lib\model.js:4058:13)
    at toExecute.push.error (C:\Project\Image\node_modules\mongoose\lib\model.js:2238:22)
    at C:\Project\Image\node_modules\async\internal\parallel.js:31:39
    at eachOfArrayLike (C:\Project\Image\node_modules\async\eachOf.js:65:9)
    at exports.default (C:\Project\Image\node_modules\async\eachOf.js:9:5)
    at _parallel (C:\Project\Image\node_modules\async\internal\parallel.js:30:5)
    at parallelLimit (C:\Project\Image\node_modules\async\parallel.js:88:26)
    at utils.promiseOrCallback.cb (C:\Project\Image\node_modules\mongoose\lib\model.js:2248:5)
    at Object.promiseOrCallback (C:\Project\Image\node_modules\mongoose\lib\utils.js:222:14)
  errors:
   { image:
      { CastError: Cast to String failed for value "{}" at path "image"
          at MongooseError.CastError (C:\Project\Image\node_modules\mongoose\lib\error\cast.js:29:11)
          at model.$set (C:\Project\Image\node_modules\mongoose\lib\document.js:875:7)
          at model._handleIndex (C:\Project\Image\node_modules\mongoose\lib\document.js:684:14)
          at model.$set (C:\Project\Image\node_modules\mongoose\lib\document.js:641:22)
          at model.Document (C:\Project\Image\node_modules\mongoose\lib\document.js:112:12)
          at model.Model (C:\Project\Image\node_modules\mongoose\lib\model.js:64:12)
          at new model (C:\Project\Image\node_modules\mongoose\lib\model.js:4058:13)
          at toExecute.push.error (C:\Project\Image\node_modules\mongoose\lib\model.js:2238:22)
          at C:\Project\Image\node_modules\async\internal\parallel.js:31:39
          at eachOfArrayLike (C:\Project\Image\node_modules\async\eachOf.js:65:9)
          at exports.default (C:\Project\Image\node_modules\async\eachOf.js:9:5)
          at _parallel (C:\Project\Image\node_modules\async\internal\parallel.js:30:5)
          at parallelLimit (C:\Project\Image\node_modules\async\parallel.js:88:26)
          at utils.promiseOrCallback.cb (C:\Project\Image\node_modules\mongoose\lib\model.js:2248:5)
          at Object.promiseOrCallback (C:\Project\Image\node_modules\mongoose\lib\utils.js:222:14)
          at Function.create (C:\Project\Image\node_modules\mongoose\lib\model.js:2209:16)
        message: 'Cast to String failed for value "{}" at path "image"',
        name: 'CastError',
        stringValue: '"{}"',
        kind: 'String',
        value: {},
        path: 'image',
        reason: [Object] } },
  _message: 'Blog validation failed',
  name: 'ValidationError' }

1 个答案:

答案 0 :(得分:0)

1)您将文件数量设置为0时选择了错误的选项。将其设置为等于一:

var cpUpload = upload.fields([{ name: 'image', maxCount: 1 }]);

2)从根目录到存储路径是一个坏主意。做亲戚:

cb(null, 'uploads/')