springboot接口直接返回文件数据流

该代码片段展示了如何在SpringBoot应用中,通过@GetMapping接口直接返回静态资源文件(如aaa.mp3)的数据流。它使用ClassPathResource读取文件,然后设置HttpHeaders以提供Content-Disposition信息,使浏览器以附件形式下载文件。
摘要由CSDN通过智能技术生成

springboot后端接口直接返回文件数据流

@GetMapping("/aaaaa")
public ResponseEntity<byte[]> getImageAsByteArray(HttpServletResponse response) throws IOException {
    ClassPathResource classPathResource = new ClassPathResource("static/aaa.mp3");
    InputStream inputStream = classPathResource.getInputStream();
    int fileLength = (int) classPathResource.getFile().length();
    byte bytes[] = new byte[fileLength];
    inputStream.read(bytes);
    inputStream.close();

    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Disposition", "attachment; filename=\"aaa.mp3\"");
    ResponseEntity<byte[]> aaaaa = new ResponseEntity(bytes, headers, HttpStatus.OK);

    return aaaaa;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值