我是REST的新手。我必须想出Rest Controller,它将文件名作为参数并显示其内容。下面是代码
@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
等所有文件格式,并显示内容并发送内容在回应。
有人可以建议我这方法吗?
答案 0 :(得分:1)
实现此目的的最佳方法是使用单独的映射(方法),这将为您生成特定的格式。
@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
}
}
然后,您可以获得特定类型的以下请求网址
/paths/pdf
和
/paths/xlsx