問題如下:
maven建構的springboot工程下的,檔案路徑
希望web端能夠下載下傳這裡的“assess_remplate.docx”檔案。
解決:
1、通過resource擷取到檔案
ClassPathResource resource = new ClassPathResource("docs/assess_template.docx");
File file = resource.getFile();
2、但是springboot工程打成jar包後,file是無法從jar包内的路徑拿到的。程式會抛出異常:
3、改用輸入流去擷取。
ClassPathResource resource = new ClassPathResource("docs/assess_template.docx");
InputStream inputStream = resource.getInputStream();
4、然後需要将位元組流轉為位元組數組。通過ResponseEntity傳回到web端。
@GetMapping("/assess_template")
public ResponseEntity download(HttpServletResponse response) throws Exception {
ClassPathResource resource = new ClassPathResource("docs/assess_template.docx");
InputStream inputStream = resource.getInputStream();
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inputStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
HttpHeaders headers = new HttpHeaders();
String downloadFielName = new String("assess_template.docx".getBytes("UTF-8"), "iso-8859-1");
headers.setContentDispositionFormData("attachment", downloadFielName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity(in2b, headers, HttpStatus.CREATED);
}