在Node.js中发送表单数据时,req.files不存在

时间:2018-08-15 16:29:07

标签: javascript node.js

我想将表单数据与文件一起存储。当我使用不带有此enctype="multipart/form-data"的表单时,效果很好,但是req.files剂量存在于需要上传文件的req中。当我使用enctype形式时,仍然存在req.files主题,而req.body没有任何数据。 我试图实现multer来处理文件,但是req.files文件存在,所以没有任何想法。 我的路线

const urlencodedParser = bodyParser.urlencoded({extended: true});
router.post('/save_file', urlencodedParser, home.add_file);

我的控制器

exports.add_file = function(req, res){
  console.log(req.body);
  console.log(req.files);
}

将提供任何帮助。

2 个答案:

答案 0 :(得分:0)

bodyParser ,用于解析服务器请求的库,不解析文件,您需要使用其他库,( multer 非常好,简单)。 所以首先:

  1. 安装Multer:npm install multer --save
  2. 此处是Multer的链接:https://github.com/expressjs/multer
  3. 使用此示例作为基础:

let multer = require("multer"); //the library
let storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'path/to/upload/your/file');
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});//Configure the place you will upload your file

let upload = multer({ storage: storage }); //instanciation of multer
// image is the name of the input in the form
router.post('/your_endpoint', upload("image"), (req, res)=> {
  let file = req.file; //contains the file
  let path = file.path; //contains the paths
})

答案 1 :(得分:0)

相关问题