BodyParser parse data instead of connect-multiparty in node.js

自古美人都是妖i 提交于 2019-12-13 08:58:27

问题


I am trying to upload file using connect-multiparty with reference of connect-multiparty below is my express.js config for that.

app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(bodyParser.json());

    //file upload configuration
    app.use(multipart({
            uploadDir: config.tmp
    }));

but when I upload file than it gives me request size if too long. I search for this and found that I need to set limit so I have also put limit parameter like below:

app.use(bodyParser.json({limit:'50mb'}));

but after that I start getting Invalid json error. than I found that bodyParser could not parse multi-part data. but i don't know how can i use multipart middleware to parse multi-part data.


回答1:


You can use node-formidable module to handle multipart form data:

var formidable = require('formidable');

app.post('/upload', function(req, res, next) {
  var form = new formidable.IncomingForm();
  form.parse(req, function(err, fields, files) {
      console.log(fields);
      console.log(files);
      res.send('done');
  });
});



回答2:


Use either bodyParser or connect-multiparty to parse request.
Both cannot be used at same time. You can parse json with connect-multiparty than why use bodyParser but bodyParser cannot parse multipart forms so we need to use other parsers like connect-multparty.
see this link.




回答3:


index.html code

<html><body>
<div id="main-content">
    <form action="upload" method="post" enctype="multipart/form-data">
         <input type="text" name="FirstName" ><br>
             <input type="text" name="LastName" ><br>
            <input type="submit">
            </div>
</div></body>
</html>

server.js

var express = require('express');
var app = express();
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();

app.use("/",  express.static(__dirname + '/client/'));

app.post('/upload', multipartMiddleware, function(req, resp) {
    console.log(req);
  console.log(req.body);
  // don't forget to delete all req.files when done
});

app.listen(3000,function(){
console.log("App Started on PORT 3000");
});


来源:https://stackoverflow.com/questions/30014422/bodyparser-parse-data-instead-of-connect-multiparty-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!