【发布时间】:2020-04-24 17:27:55
【问题描述】:
我正在尝试使用 multer 在 expressJS 中上传文件。我正在使用邮递员并将标头设置为 multipart/form-data 我需要首先使用 Joi 验证请求正文,但是当我尝试首先放置 Joi 验证中间件时,它不起作用。当我首先放置 multer 中间件时,即使请求正文没有通过 Joi 中间件的验证,上传也能正常工作。我该如何解决这个问题?
【问题讨论】:
我正在尝试使用 multer 在 expressJS 中上传文件。我正在使用邮递员并将标头设置为 multipart/form-data 我需要首先使用 Joi 验证请求正文,但是当我尝试首先放置 Joi 验证中间件时,它不起作用。当我首先放置 multer 中间件时,即使请求正文没有通过 Joi 中间件的验证,上传也能正常工作。我该如何解决这个问题?
【问题讨论】:
我遇到了类似的问题,经过一些搜索和尝试和错误,这解决了我。需要记住的是在 multer 上传之后放置 Joi 验证器并稍微更改验证方案。
我已经将代码压缩到一个文件中以使其更清晰一些,所以它缺少它的依赖关系,我希望你明白:
const createFile = {
body: {
name: Joi.string().required(),
description: Joi.string(),
protected: Joi.boolean().required()
},
file: Joi.string().required()
};
router
.route('/files')
.post(upload.single('file'), validate(createFile), (req, res, next) => {
//controller logic
}
);
/**
* @swagger
* path:
* /files:
* post:
* summary: Upload a file and its metadata to the server.
* description: Create a file.
* consumes:
* - multipart/form-data
* tags: [Files]
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* multipart/form-data:
* schema:
* type: object
* required:
* - name
* - protected
* - file
* properties:
* name:
* type: string
* description:
* type: string
* protected:
* type: boolean
* default: false
* file:
* type: string
* format: binary
* responses:
* "201":
* description: Created
* content:
* application/json:
* schema:
* type: object
* properties:
* success:
* type: boolean
* message:
* type: string
* data:
* type: object
* $ref: '#/components/schemas/File'
* "401":
* $ref: '#/components/responses/Unauthorized'
* "403":
* $ref: '#/components/responses/Forbidden'
*/
【讨论】: