如何使用 spring 和球衣制作多种媒体类型
How to produce multiple media type using spring and jersey
我是 REST.I 的新手,必须想出 Rest Controller,它将文件名作为参数并显示其 contents.Below 是代码
@RequestMapping(value = "/paths", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<InputStreamResource> downloadPDFFile() throws IOException {
ClassPathResource pdfFile = new ClassPathResource("PACKING LIST PDF 3000730933.pdf");
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity.ok().headers(headers).contentLength(pdfFile.contentLength())
.body(new InputStreamResource(pdfFile.getInputStream()));
}
上面的代码将显示 pdf 的内容,因为提到了 produces = "application/pdf"
。我想要通用代码,可以采用所有文件格式,如 image
、doc
、docx
、xls
、xlsx
并显示内容并发送内容在响应中。
任何人都可以给我建议这个方法吗?
实现此目的的最佳方法是使用单独的映射(方法),这将为您生成特定格式。
@RequestMapping(value = "/paths")
public class YourApplication
{
@RequestMapping(value = "/pdf", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<InputStreamResource> downloadPDFFile() throws IOException {
// you code for pdf
}
@RequestMapping(value = "/xlsx", method = RequestMethod.GET, produces = "application/xlsx")
public ResponseEntity<InputStreamResource> downloadXLSXFile() throws IOException {
// you code for xlsx
}
}
然后,您可以针对特定类型
提出以下请求url
/paths/pdf
和
/paths/xlsx
我是 REST.I 的新手,必须想出 Rest Controller,它将文件名作为参数并显示其 contents.Below 是代码
@RequestMapping(value = "/paths", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<InputStreamResource> downloadPDFFile() throws IOException {
ClassPathResource pdfFile = new ClassPathResource("PACKING LIST PDF 3000730933.pdf");
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity.ok().headers(headers).contentLength(pdfFile.contentLength())
.body(new InputStreamResource(pdfFile.getInputStream()));
}
上面的代码将显示 pdf 的内容,因为提到了 produces = "application/pdf"
。我想要通用代码,可以采用所有文件格式,如 image
、doc
、docx
、xls
、xlsx
并显示内容并发送内容在响应中。
任何人都可以给我建议这个方法吗?
实现此目的的最佳方法是使用单独的映射(方法),这将为您生成特定格式。
@RequestMapping(value = "/paths")
public class YourApplication
{
@RequestMapping(value = "/pdf", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<InputStreamResource> downloadPDFFile() throws IOException {
// you code for pdf
}
@RequestMapping(value = "/xlsx", method = RequestMethod.GET, produces = "application/xlsx")
public ResponseEntity<InputStreamResource> downloadXLSXFile() throws IOException {
// you code for xlsx
}
}
然后,您可以针对特定类型
提出以下请求url/paths/pdf
和
/paths/xlsx