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

Java 与Spring Boot同时提供JSON响应和下载文件,java,spring,spring-boot,Java,Spring,Spring Boot,要求: 我需要创建一个RESTAPI,它允许下载文件和JSON响应 我已经有两个不同的API来解决这个问题,但是现在我需要将这些API合并到一个API中 public ResponseEntity<InputStreamResource> downloadFile1( @RequestParam(defaultValue = DEFAULT_FILE_NAME) String fileName) throws IOException { Media

要求: 我需要创建一个RESTAPI,它允许下载文件和JSON响应

我已经有两个不同的API来解决这个问题,但是现在我需要将这些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);
}
公共响应下载文件1(
@RequestParam(defaultValue=默认文件名)字符串文件名)引发IOException{
MediaType MediaType=MediaTypeUtils.getMediaTypeForFileName(this.servletContext,fileName);
System.out.println(“文件名:“+fileName”);
System.out.println(“mediaType:+mediaType”);
文件文件=新文件(目录+“/”+文件名);
InputStreamResource资源=新的InputStreamResource(新文件InputStream(文件));
返回ResponseEntity.ok()
//内容配置
.header(HttpHeaders.CONTENT_处置,“附件;文件名=“+file.getName())
//内容类型
.contentType(mediaType)
//内容长度
.contentLength(文件.length())//
.机构(资源);
}

上面是只返回要下载的文件的现有代码,但我还需要一个json响应

您需要返回多部分内容。例如,见

代码

@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);
}
@GET
@产生(“多部分/混合”)
公共MultipartBody getMulti2(@QueryParam(“name”)字符串名){
列表附件=新建LinkedList();
add(新的附件(“root”,“application/json”,service.getEntity(name));
add(新附件(“图像”、“应用程序/八位字节流”、service.getEntityData(名称));
返回新的MultipartBody(附件,true);
}

I'm get multipart为Null,每当我使用products=“multipart/mixed”时,没有适配器为apache multipart处理Null,如果我不使用它,那么我会得到Object1和Object2的Json。Object1包含我想要的json,但object2应该是一个可以下载的文件。有什么解决办法吗?