我想使用 express 框架上传多部分表单数据。我正在使用 swagger-node为我的 API 使用 express。现在,我在 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"
但现在我不知道如何使用它上传图片。是否有任何内置工具可以 Swagger 上传图像?
最佳答案
尽管这是一个老问题,但这里的问题是如何做到这一点。我们在这里使用 express-fileupload
npm 模块,这让我们的生活更轻松。下面是一个简单的片段,用于将文件上传并保存到我们的服务器,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"
});
});
}
note: The above code is for a single & simple use case, you may need to do some more configurations based on your requirements. If you simply want to upload a file and store it on the server this should work.
这里需要注意的一件重要事情是,swagger 不必知道我们正在使用哪个模块,或者 swagger 也不提供用于上传图像的内置工具。
我们在问题中声明我们的 API 时所做的,更具体地说是这些行......
parameters:
- in: formData
name: imageFile
type: file
description: The file to upload.
required: true
... 指定上述 POST API 需要一个名为 imageFile
的参数,该参数应该是一个文件并且是此 API 运行所必需的。如果在您的 express 和 swagger-node 配置中启用了 swagger validator 中间件,我们的 API 将验证传入的请求并以 400 Bad Request
错误响应,以防文件未上传。
如果您想要 swagger-node
、swagger-tools
和 swagger express 中间件的示例配置,您可以在 this answer 中找到一些详细信息由我发布(抱歉宣传:P)
关于node.js - 如何使用 swagger-express-mw 和 express 上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45398963/