use*_*.14 6 node.js express swagger
我想使用快速框架上传多部分表单数据。我正在为我的 API使用带有 express 的swagger-node。现在,我在 swagger YAML 文件中编写了以下内容以上传文件:
/picture/students:
# binds a127 app logic to a route
x-swagger-router-controller: bus_api
post:
description: Upload a picture
# used as the method name of the controller
operationId: uploadStudentPic
consumes:
- multipart/form-data
parameters:
- in: formData
name: imageFile
type: file
description: The file to upload.
required: true
responses:
"200":
description: OK
schema:
# a pointer to a definition
$ref: "#/definitions/SuccessResponseStr"
Run Code Online (Sandbox Code Playgroud)
但现在我不知道如何使用它上传图片。是否有任何内置工具可以在 swagger 中上传图像?
尽管这是一个老问题,但你如何才能做到这一点。我们在这里使用express-fileuploadnpm 模块,这让我们的生活更轻松。下面是一个简单的代码片段,用于将文件上传并保存到我们的服务器,swagger yaml 保持不变。
//import the module
const fileUpload = require('express-fileupload');
// Add this in express setup
app.use(fileUpload());
// Your controller function, where you will get the file and store it as needed
function uploadStudentPic(req: any, res: any, next: any) {
var startup_image = req.files.imageFile;
var fileName = startup_image.name;
startup_image.mv(__dirname + '/images/' + fileName, function (err: any) {
if (err) {
res.status(500).send(err);
}
res.json({
"message": "File Uploaded"
});
});
}
Run Code Online (Sandbox Code Playgroud)
注意:以上代码适用于单个简单用例,您可能需要根据您的要求进行更多配置。如果您只想上传文件并将其存储在服务器上,这应该可行。
这里需要注意的重要一点是,swagger 不需要知道我们正在使用哪个模块,或者 swagger 也不提供上传图像的内置设施。
我们在问题中声明我们的 API 时正在做什么,更具体地说是这些行......
parameters:
- in: formData
name: imageFile
type: file
description: The file to upload.
required: true
Run Code Online (Sandbox Code Playgroud)
...指定上述 POST API 需要一个名为的参数,imageFile该参数应该是一个文件,并且是该 API 运行所必需的。如果在您的 Express 和 swagger-node 配置中启用了 swagger 验证器中间件,我们的 API 将验证传入的请求,并400 Bad Request在文件未上传的情况下响应错误。
swagger-node如果您想要使用swagger Express 中间件的示例配置swagger-tools,您可以在我发布的这个答案中找到一些详细信息(抱歉公开:P)
| 归档时间: |
|
| 查看次数: |
1343 次 |
| 最近记录: |