我有一个带有文件上传方法的 Jersey 服务,看起来像这样(简化):
@POST
@Path("/{observationId : [a-zA-Z0-9_]+}/files")
@Produces({ MediaType.APPLICATION_JSON})
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(
value = "Add a file to an observation",
notes = "Adds a file to an observation and returns a JSON representation of the uploaded file.",
response = ObservationMediaFile.class
)
@ApiResponses({
@ApiResponse(code = 404, message = "Observation not found. Invalid observation ID."),
@ApiResponse(code = 406, message= "The media type of the uploaded file is not supported. Currently supported types are 'images/*' where '*' can be 'jpeg', 'gif', 'png' or 'tiff',")
})
public RestResponse<ObservationMediaFile> addFileToObservation(
@PathParam("observationId") Long observationId,
@FormDataParam("file") InputStream is,
@FormDataParam("file") FormDataContentDisposition fileDetail,
@FormDataParam("fileBodyPart") FormDataBodyPart body
){
MediaType type = body.getMediaType();
//Validate the media type of the uploaded file...
if( /* validate it is an image */ ){
throw new NotAcceptableException("Not an image. Get out.");
}
//do something with the content of the file
try{
byte[] bytes = IOUtils.toByteArray(is);
}catch(IOException e){}
//return response...
}
它可以工作,我可以使用 Chrome 中的 Postman 扩展成功测试它。
但是,Swagger 看到 2 个名为“file”的参数。不知何故,它似乎理解InputStream
参数和FormDataContentDisposition
参数实际上是同一file
参数的 2 个部分,但它看不到FormDataBodyPart
参数。
这是参数的 Swagger JSON:
parameters: [
{
name: "observationId",
required: true,
type: "integer",
format: "int64",
paramType: "path",
allowMultiple: false
},
{
name: "file",
required: false,
type: "File",
paramType: "body",
allowMultiple: false
},
{
name: "fileBodyPart",
required: false,
type: "FormDataBodyPart",
paramType: "form",
allowMultiple: false
}]
因此,Swagger UI 为 FormDataBodyPart 参数生成一个文件选择器字段和一个额外的文本字段:
因此,当我在 Swagger UI 中选择一个文件并提交表单时,我最终会读取 InputStream 中文本字段的内容,而不是上传文件的内容。如果我将文本字段留空,我会得到文件的名称。
如何指示 Swagger 忽略 FormDataBodyPart 参数?
或者,作为一种解决方法,如何在没有 FormDataBodyPart 对象的情况下获取上传文件的媒体类型?
我使用 Jersey 2.7 和 swagger-jersey2-jaxrs_2.10 版本 1.3.4。