使用 Springfox 记录多部分/表单数据端点

问题描述 投票:0回答:1

我有一个 POST 端点,它接收 @ModelAttribute 参数。一切正常,但 swagger 文档没有描述、示例等。

我正在使用java 11,springboot 2.5.4和springfox-boot-starter 3.0.0

这是我的代码:

@Api
@RestController
@RequestMapping("/foo")
@Validated
public class MyRest {
    @PostMapping(value = "/{id}/bar", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
    @ApiOperation(value = "Do nothing", notes = "This endpoint does nothing")
    public ResponseEntity<String> search(
            @ModelAttribute MyModelRequest request,

            @ApiParam(value = "Folder ID", required = true)
            @PathVariable String id) {
        // some business code
        return new ResponseEntity<>("lorem ipsum", HttpStatus.OK);
    }
}

我的模型请求

@ApiModel
@Data
public class MyModelRequest {

    @ApiParam(name = "fileName", value = "The name of the image to be stored in database")
    @ApiModelProperty(value = "name model description", example = "summer picture", required = true)
    private String name;

    @DecimalMin("0.00")
    @DecimalMax("100.00")
    @ApiParam(name = "accuracy", value = "The required accuracy")
    @ApiModelProperty(value = "Minimum required accuracy", example = "95.15", required = false)
    private BigDecimal accuracy;

    @ApiParam(name = "marginTop", value = "Top margin of the image")
    @ApiModelProperty(value = "Separation between top item and the image", example = "300", required = false)
    private Integer marginTop;

    @ApiParam(name = "image")
    @ApiModelProperty(value = "The image to be stored", example = "vacations.png", required = true)
    private MultipartFile image;
}

这是生成的 swagger 文档

更新:我注意到,如果我将

consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }
更改为
consumes = { MediaType.APPLICATION_JSON_VALUE }
或从端点中删除整个“consumes”参数,文档会正确显示,但是,这样做会使文件上传失败。

java swagger-ui springfox
1个回答
0
投票

我已在我的控制器中使用此配置。

@Operation(summary = "Send mail", description = "Send mail simple")
@ApiResponses({
        @ApiResponse(responseCode = "200", description = "Success", content = {
                @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ResponseDTO.class))
        }),
        @ApiResponse(responseCode = "500", description = "Internal Server Error", content = {
                @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ResponseErrorDTO.class))
        })
})
@PostMapping(value = "/sendMessageFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
// ModelAttribute -> send from data with byte
public ResponseEntity<Object> receiveRequestEmailWithFile(@ModelAttribute EmailFileDTO emailFileDTO) {

    HttpStatus httpStatus = HttpStatus.OK;
    System.out.println("Message received" + emailFileDTO);

    try {
        String fileName = emailFileDTO.file().getOriginalFilename();

        Path path = Paths.get("src/mail/resources/files/" + fileName);

        Files.createDirectories(path.getParent()); //create directory if not exists
        Files.copy(emailFileDTO.file().getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); // if the file exists, delete and replace it

        File file = path.toFile();

        emailService.sendEmailWithFile(emailFileDTO.toUser(), emailFileDTO.subject(), emailFileDTO.message(), file);

        ResponseDTO response = ResponseDTO.builder()
                .code(httpStatus.toString())
                .status("Email sent with file")
                .build();

        return ResponseEntity.ok(response);

    } catch (Exception e) {
        // throw new RuntimeException("Error sent email with file." + e.getMessage());
        ResponseErrorDTO responseErrorDTO = new ResponseErrorDTO(e.getMessage(), "Error sent email with file");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(responseErrorDTO);
    }
}

使用相同的(消耗= MediaType.MULTIPART_FORM_DATA_VALUE)

@PostMapping(值=“/sendMessageFile”,消耗= MediaType.MULTIPART_FORM_DATA_VALUE)

这是我用过的记录

公共记录EmailFileDTO( @NotBlank @Schema(description = "向用户发送电子邮件", name = "toUser", type = "Array[]", example = "[" + " "[电子邮件受保护]" ” + “]”) 字符串[]到用户,

    @NotBlank
    @Schema(description = "Email Subject", name = "subject", type = "String", example = "Example of subject 2024")
    String subject,

    @NotBlank
    @Schema(description = "Body of Message", name = "message", type = "String", example = "Example of body the message, not response please!")
    String message,

    @NotBlank
    @Schema(description = "File attached to email", name = "file", type = "string", format = "binary")
    MultipartFile
            file) {

}

在此输入图片描述

这对我用 Swagger 发送电子邮件很有用。

希望我的代码对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.