[英]Provide JSON response and download file simultaneously with Spring-Boot
要求:我需要创建一个Rest API,该API可以下载文件以及JSON响应。
我已经有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);
}
上面是仅返回文件下载的现有代码,但我也需要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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.