Sails.js req.files为空,req.body.image未定义

Sails.js req.files is empty and req.body.image is undefined

本文关键字:req body image 未定义 为空 js files Sails      更新时间:2023-09-26

从昨天开始,我就一直在努力理解这一点,但我找不到任何解决方案,即使是询问谷歌和StackOverFlow。问题是,我正在构建一个项目,其中包含"产品"模型、控制器和视图。在new.ejs视图中,我有一个包含文件标记(命名为image)的表单。因此,在控制器上,我试图通过在控制台中记录req.files.image.path来获取图像路径,但req.files是空的。我还试着显示req.body.image,它是未定义的。

以下是客户端代码(views/product/new.ejs):

(这是一个Sails.js应用程序)

以下是客户端代码(视图/产品/新):

<div class='container'>
    <form action='/product/create' role='form' class='form-signin' enctype="multipart/form-data" id='product-form'>
        <div class='form-group'>
            <label class='sr-only' for='name'>Name of the product</label>
            <input type="text" class='form-control' placeholder="Name" name='name' id='name' />
        </div>
        <div class='form-group'>
            <label class='sr-only' for='image'>Image of the product</label>
            <input type="file" name='image' id='image' />
        </div>
.
.
.etc...

这里是服务器端(api/controllers/ProductController.js):

'create': function(req, res, next) {
    // Include the node file module
    var fs = require('fs');
    console.log(req.files); //This logs : { } in the console
    console.log(req.body.image); //This logs : undefined in the console
    //Readfile with fs doesn't work cause req.files is empty
    // fs.readFile(req.files.image.path, function(error, data) {
    //  //get image name
    //  var imageName = req.files.data.name;
    //  //if enable to get name
    //  if (!imageName) {
    //      console.log('error uploading image');
    //      res.redirect('/product/new');
    //      //Else if we have an image
    //  } else {
    //      //change the path to our own
    //      var newPath = __dirname + '/assets/images/products/fullsize/' + imageName;
    //      fs.writeFile(newPath, data, function(error) {
    //          console.log(newPath);
    //          //res.redirect('/product' + imageName);
    //      });
    //  }
    // });
}

谢谢你的帮助。

Mat。

此处也提供:https://github.com/balderdashy/sails/issues/1127

在html表单中使用method=post