Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

javascript - Multipart form data post method using express js

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...