如何配置Swagger UI,Jersey和文件上传?

时间:2014-04-17 15:04:55

标签: java rest jersey swagger swagger-ui

我有一个带有文件上传方法的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个名为&#34; file&#34;的参数。不知何故,它似​​乎理解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

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

如何指示Swagger忽略FormDataBodyPart参数?

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

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

2 个答案:

答案 0 :(得分:4)

为泽西创建一个swagger过滤器,然后将参数标记为内部或您要过滤的其他字符串。这个例子也显示了这个:

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>

答案 1 :(得分: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“不可见”。

更新:如果没有定义其他资源(@Pa​​th注释),而不采用FormDataContentDisposition,则此方法有效。如果有则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());
}