6

我有一个带有文件上传方法的 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 参数生成一个文件选择器字段和一个额外的文本字段:

大摇大摆的ui

因此,当我在 Swagger UI 中选择一个文件并提交表单时,我最终会读取 InputStream 中文本字段的内容,而不是上传文件的内容。如果我将文本字段留空,我会得到文件的名称。

如何指示 Swagger 忽略 FormDataBodyPart 参数?

或者,作为一种解决方法,如何在没有 FormDataBodyPart 对象的情况下获取上传文件的媒体类型?

我使用 Jersey 2.7 和 swagger-jersey2-jaxrs_2.10 版本 1.3.4。

4

2 回答 2

4

为 jersey 创建一个 swagger 过滤器,然后将参数标记为 internal 或您正在过滤的其他字符串。此示例中也显示了这一点:

https://github.com/wordnik/swagger-core/blob/master/samples/java-jaxrs/src/main/java/com/wordnik/swagger/sample/util/ApiAuthorizationFilterImpl.java

您的服务方法将具有此参数注释

@ApiParam(access = "internal") @FormDataParam("file") FormDataBodyPart body,

您的过滤器会像这样查找它:

public boolean isParamAllowed(Parameter parameter, Operation operation, ApiDescription api,
        Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) {
    if ((parameter.paramAccess().isDefined() && parameter.paramAccess().get().equals("internal")))
        return false;
    else
        return true;
}

为球衣注册您的 swagger 过滤器,然后它不会返回该字段,并且 swagger-ui 不会显示它,这将解决您的上传问题。

<init-param>
      <param-name>swagger.filter</param-name>
      <param-value>your.company.package.ApiAuthorizationFilterImpl</param-value>
    </init-param>
于 2014-04-27T17:57:25.510 回答
3

目前尚不清楚何时将其添加到 Jersey,但 Multipart 部分末尾的注释说“ @FormDataParam 注释也可以用于字段”。果然你可以这样做:

@FormDataParam(value="file") FormDataContentDisposition fileDisposition;
@FormDataParam("fileBodyPart") FormDataBodyPart body;

@Path("/v1/source")
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON})
@ApiOperation(
        value = "Create a new Source from an uploaded file.",
        response = Source.class
        )
public Response makeSource(
        @FormDataParam(value="file") InputStream inputStream
        )
{
    logger.info(fileDisposition.toString());
    return makeSourceRaw(inputStream, fileDisposition.getFileName());
}

这提供了 FormDataContentDisposition,但使其对 Swagger “不可见”。

更新:这有效,但如果定义了其他不采用 FormDataContentDisposition 的资源(@Pa​​th 注释),则无效。如果有,则 Jersey 在运行时会失败,因为它无法填写 fileDisposition 字段。

如果您使用最新版本的 Swagger 来简单地将参数标记为隐藏,那么这是一个更好的解决方案。

@FormDataParam("fileBodyPart") FormDataBodyPart body;

@Path("/v1/source")
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON})
@ApiOperation(
        value = "Create a new Source from an uploaded file.",
        response = Source.class
        )
public Response makeSource(
        @FormDataParam(value="file") InputStream inputStream,
        @ApiParam(hidden=true) @FormDataParam(value="file") FormDataContentDisposition fileDisposition;

        )
{
    logger.info(fileDisposition.toString());
    return makeSourceRaw(inputStream, fileDisposition.getFileName());
}
于 2015-09-03T23:06:02.520 回答