使用Express JS的多部分表单数据发布方法 [英] Multipart form data post method using express js

查看:75
本文介绍了使用Express JS的多部分表单数据发布方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将表单数据发布到我的快速js服务器端.这是我的pug文件

form(action="/profile" method="post" enctype="multipart/form-data")
 input(type="file" accept="image/*" name="profileimage")
 input(type="text" name="username")
 input(type="submit" value="Upload")

之后,我尝试在服务器端js中使用req.body记录发布数据,如下所示.那是我的profile.js

router.post('/', function (req, res) {
  console.log('Body- ' + JSON.stringify(req.body));
});

这是我的控制台结果 body- {}

如果我不像form(action="/profile" method="post")那样发布enctype="multipart/form-data",则可以从控制台结果中获取发布数据.

解决方案

您需要使用中间件来处理多部分表单数据,我认为最著名的是 multer .

您可以在这里找到它: https://github.com/expressjs/multer

要使用它:

  1. 首先在根项目中使用npm install --save multer将其添加到您的模块中
  2. 然后将其导入您的.js文件var multer = require('multer');
  3. 通过在multer构造函数中设置dest参数来选择上传目录:var upload = multer({ dest: 'uploads/' });
  4. 现在只需将其作为中间件传递给POST函数,如下所示:

router.post('/', upload, function (req, res) { console.log('Body- ' + JSON.stringify(req.body)); });

别忘了在github仓库中阅读文档.

I tried to post form data to my express js server side. This is my pug file

form(action="/profile" method="post" enctype="multipart/form-data")
 input(type="file" accept="image/*" name="profileimage")
 input(type="text" name="username")
 input(type="submit" value="Upload")

After that I tried to log the post data with req.body inside server side js as follow. That is my profile.js

router.post('/', function (req, res) {
  console.log('Body- ' + JSON.stringify(req.body));
});

And this is my console result body- {}

If I post without enctype="multipart/form-data" like form(action="/profile" method="post"), I can get the post data from my console result.

解决方案

You need to use a middleware to handle multipart form data, i think the most famous one is multer.

You can find it here: https://github.com/expressjs/multer

To use it:

  1. First add it to your modules with npm install --save multer in your root project
  2. Then import it in your .js file var multer = require('multer');
  3. Choose your upload directory by setting the dest argument in the multer constructor: var upload = multer({ dest: 'uploads/' });
  4. Now just pass it as a middleware in your POST function as follows:

router.post('/', upload, function (req, res) { console.log('Body- ' + JSON.stringify(req.body)); });

And don't forget to read the documentation at their github repo.

这篇关于使用Express JS的多部分表单数据发布方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆