File uploading with Express 4.0: req.files undefined

后端 未结 9 1773
感动是毒
感动是毒 2020-11-22 10:10

I\'m attempting to get a simple file upload mechanism working with Express 4.0 but I keep getting undefined for req.files in the app.post

相关标签:
9条回答
  • 2020-11-22 11:08

    The body-parser module only handles JSON and urlencoded form submissions, not multipart (which would be the case if you're uploading files).

    For multipart, you'd need to use something like connect-busboy or multer or connect-multiparty (multiparty/formidable is what was originally used in the express bodyParser middleware). Also FWIW, I'm working on an even higher level layer on top of busboy called reformed. It comes with an Express middleware and can also be used separately.

    0 讨论(0)
  • 2020-11-22 11:09

    It looks like body-parser did support uploading files in Express 3, but support was dropped for Express 4 when it no longer included Connect as a dependency

    After looking through some of the modules in mscdex's answer, I found that express-busboy was a far better alternative and the closest thing to a drop-in replacement. The only differences I noticed were in the properties of the uploaded file.

    console.log(req.files) using body-parser (Express 3) output an object that looked like this:

    { file: 
       { fieldName: 'file',
         originalFilename: '360px-Cute_Monkey_cropped.jpg',
         name: '360px-Cute_Monkey_cropped.jpg'
         path: 'uploads/6323-16v7rc.jpg',
         type: 'image/jpeg',
         headers: 
          { 'content-disposition': 'form-data; name="file"; filename="360px-Cute_Monkey_cropped.jpg"',
            'content-type': 'image/jpeg' },
         ws: 
          WriteStream { /* ... */ },
         size: 48614 } }
    

    compared to console.log(req.files) using express-busboy (Express 4):

    { file: 
       { field: 'file',
         filename: '360px-Cute_Monkey_cropped.jpg',
         file: 'uploads/9749a8b6-f9cc-40a9-86f1-337a46e16e44/file/360px-Cute_Monkey_cropped.jpg',
         mimetype: 'image/jpeg',
         encoding: '7bit',
         truncated: false
         uuid: '9749a8b6-f9cc-40a9-86f1-337a46e16e44' } }
    
    0 讨论(0)
  • 2020-11-22 11:11

    express-fileupload looks like the only middleware that still works these days.

    With the same example, multer and connect-multiparty gives an undefined value of req.file or req.files, but express-fileupload works.

    And there are a lot of questions and issues raised about the empty value of req.file/req.files.

    0 讨论(0)
提交回复
热议问题