与 Spring-Boot 同时提供 JSON 响应和下载文件

iam*_*ulK 4 java spring spring-boot

要求: 我需要创建一个可以允许下载文件和 JSON 响应的 Rest API。

我已经有 2 个不同的 API 来解决这个问题,但现在我需要将这些 API 合并为一个。

public ResponseEntity<InputStreamResource> downloadFile1(
            @RequestParam(defaultValue = DEFAULT_FILE_NAME) String fileName) throws IOException {


    MediaType mediaType = MediaTypeUtils.getMediaTypeForFileName(this.servletContext, fileName);
    System.out.println("fileName: " + fileName);
    System.out.println("mediaType: " + mediaType);

    File file = new File(DIRECTORY + "/" + fileName);
    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

    return ResponseEntity.ok()
            // Content-Disposition
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
            // Content-Type
            .contentType(mediaType)
            // Contet-Length
            .contentLength(file.length()) //
            .body(resource);
}
Run Code Online (Sandbox Code Playgroud)

以上是仅返回要下载的文件的现有代码,但我也需要一个 json 响应。

Sta*_*avL 6

您需要返回 Multipart 内容。见例如

https://github.com/juazugas/spring-boot-multipart/blob/master/src/main/java/com/example/demo/server/MultiEndpoint.java

编码

@GET
@Produces("multipart/mixed")
public MultipartBody getMulti2(@QueryParam("name") String name) {
    List<Attachment> attachments = new LinkedList<>();
    attachments.add(new Attachment("root", "application/json", service.getEntity(name)));
    attachments.add(new Attachment("image", "application/octet-stream", service.getEntityData(name)));
    return new MultipartBody(attachments, true);
}
Run Code Online (Sandbox Code Playgroud)