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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23136748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 20:59:46  来源:igfitidea点击:

How to configure Swagger UI, Jersey and file upload?

javarestjerseyswaggerswagger-ui

提问by Pierre Henry

I have a Jersey service with a file upload method that looks like this (simplified):

我有一个带有文件上传方法的 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...
}

It works and I can test it successfully using Postman extension in Chrome.

它有效,我可以在 Chrome 中使用 Postman 扩展成功测试它。

However, Swagger sees 2 parameters named "file". Somehow it seems to understand that the InputStreamparameter and the FormDataContentDispositionparameter are actually 2 parts of the same fileparameter, but it fails to see that for the FormDataBodyPartparameter.

但是,Swagger 看到了 2 个名为“file”的参数。不知何故,它似​​乎明白InputStream参数和FormDataContentDisposition参数实际上是同一个file参数的2 个部分,但它没有看到FormDataBodyPart参数。

This is the Swagger JSON for the parameters :

这是参数的 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
}]

As a result, Swagger UI generates a file picker field, and an extra text field for the FormDataBodyPart argument :

因此,Swagger UI 会为 FormDataBodyPart 参数生成一个文件选择器字段和一个额外的文本字段:

swagger ui

大摇大摆的用户界面

So when I pick a file and submit the form in Swagger UI, I end up reading the content of the text field in the InputStream instead of the content of the uploaded file. And if I leave the textfield empty, I get the name of the file.

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

How can I instruct Swagger to ignore the FormDataBodyPart parameter ?

如何指示 Swagger 忽略 FormDataBodyPart 参数?

Alternatively, as a work-around, how can I obtain the media type of the uploaded file without the FormDataBodyPart object ?

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

I use Jersey 2.7 and swagger-jersey2-jaxrs_2.10 version 1.3.4.

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

采纳答案by user2362658

Create a swagger filter for jersey and then mark the parameter as internal or some other string you are filtering on. This is also shown in this example:

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

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

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

Your service method will have this parameter annotation

你的服务方法会有这个参数注解

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

Your filter will look for it like this:

你的过滤器会像这样寻找它:

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;
}

Register your swagger filter for jersey and then it will not return that field and swagger-ui will not show it which will fix your upload problem.

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

<init-param>
      <param-name>swagger.filter</param-name>
      <param-value>your.company.package.ApiAuthorizationFilterImpl</param-value>
    </init-param>

回答by FinnTheHuman

It's unclear when this was added to Jersey but a note at the very end of the Multipart section says "@FormDataParam annotation can be also used on fields". Sure enough you can do this:

不清楚何时将其添加到 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());
}

This provides the FormDataContentDisposition but makes it "invisible" to Swagger.

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

Update: This works but not if there are other resources defined (@Path annotations) that don't take FormDataContentDisposition. If there are then Jersey fails at runtime because it can't fill in the fileDisposition field.

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

A better solution if you're using a recent version of Swagger to simply mark the parameter as hidden like so.

如果您使用最新版本的 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());
}