Proper way to use connect-multiparty with express.js?

两盒软妹~` 提交于 2019-12-24 00:44:53

问题


I am trying to upload files to my server and extract them from the post request using the connect-multiparty middleware. However, when I receive the request on the server, the req.files and req.body objects are empty (not null, but node-inspector shows that they are Objects with nothing in them.

Here is the code that I'm working with:

server.js:

var express = require( "express" );
var app = express();
var server = require( "http" ).Server( app );
var fs = require( "fs" );
var multipart = require('connect-multiparty');

app.use( express.static( "public" ) );
app.use( multipart() );

app.post( "/httpUpload", function( req, res ) {
    console.log( "Received post request" );
}

index.html:

<form action="/httpUpload" method="post" enctype="multipart/form-data">
  <input type="file" id="uploadFileInput">
  <div class="row">
    <div class="col-md-6">
      <input type="submit">
    </div>
  </div>
</form>

I've gotten similar results trying to use multer, connect-busboy, and body-parser. I would have loved if this solution worked for me, but it didn't: http://howtonode.org/really-simple-file-uploads

So ... the only common theme in all of my failed attempts is me. ;o) Any ideas what I'm doing wrong?


回答1:


Well ... this isn't quite an answer to my question, but when I changed my code to remove the form and send the post request via jQuery's ajax method, the req.files object had my data in it. (shrug) Here was the code in my js that made it work:

$.ajax( {
    url: "/httpUpload",
    type: "POST",
    processData: false, // important
    contentType: false, // important
    dataType : "json",
    data: formData
} );

This is the post that put me on the right path: File Upload without Form




回答2:


here is my way of extracting the uploaded files :

var express = require('express');
var multiparty = require('connect-multiparty'),
    multipartyMiddleware = multiparty({ uploadDir: './imagesPath' });

var router = express.Router();

router.post('/', multipartyMiddleware, function(req, res) {
  console.log(req.body, req.files);
  var file = req.files.file;
  console.log(file.name);
  console.log(file.type);
  res.status(200).send('OK');
});

module.exports = router;

this will save you uploded files to imagesPath folder



来源:https://stackoverflow.com/questions/32914272/proper-way-to-use-connect-multiparty-with-express-js

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