天天看点

springboot读取src下文件_springboot获取src/main/resource下的文件

问题如下:

maven构建的springboot工程下的,文件路径

springboot读取src下文件_springboot获取src/main/resource下的文件

希望web端能够下载这里的“assess_remplate.docx”文件。

解决:

1、通过resource获取到文件

ClassPathResource resource = new ClassPathResource("docs/assess_template.docx");

File file = resource.getFile();

2、但是springboot工程打成jar包后,file是无法从jar包内的路径拿到的。程序会抛出异常:

springboot读取src下文件_springboot获取src/main/resource下的文件

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);

}