我想使用express框架上传多部分表单数据.我正在使用 swagger-node with express for my API.现在,我已经在swagger YAML文件中写了以下文件来上传文件: /picture/students: # binds a127 app logic to a route x-sw
/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"
但现在我不知道如何使用它上传图像.是否有任何内置的设施上传图像?
虽然这是一个老问题,但你是如何做到的.我们在这里使用了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& amp;中启用了swagger验证器中间件swagger-node配置,我们的API将验证传入的请求,并在文件未上传时响应400 Bad Request错误.
如果你想要一个带有swagger express中间件的swagger-node,swagger-tools的示例配置,你可以在我发布的this answer中找到一些细节(抱歉宣传:P)
