File uploading with Express 4.0: req.files undefined

后端 未结 9 1894
感动是毒
感动是毒 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: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' } }
    

提交回复
热议问题