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

问题如下:

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

f44b1d56e0d23e007018e839dd394388.png

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

解决:

1、通过resource获取到文件

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

File file = resource.getFile();

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

9dd953c3a73a0b85d7a90a31e1364603.png

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值