SpringBoot实现下载

引自我的gitbook

下载的话有几种方法,下面这个,经测好使。 具体细节先不做解释,核心方法应该就是flushBuffer,再说吧,先拿来用。

 

@RequestMapping("download")

public void downloadFileAction(HttpServletRequest request, HttpServletResponse response) {

response.setCharacterEncoding(request.getCharacterEncoding());

response.setContentType("application/octet-stream");

FileInputStream fis = null;

try {

File file = new File("C:\\Users\\carry\\Pictures\\198109742591463b0b7396936.jpg");

fis = new FileInputStream(file);

response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());

IOUtils.copy(fis, response.getOutputStream());

response.flushBuffer();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (fis != null) {

try {

fis.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

下面是第二种方法,这是我自己测试从ftp上下载文件时测试的,和上面的一样,都是粘的,但已无从考证,原理依旧不解释,等我熟悉了再说。。。

 

@GetMapping("download")

public ResponseEntity<InputStreamResource> downloadTest() throws Exception {

File file = new File("C:\\Users\\carry\\Pictures\\zhizi.jpg");

InputStream inputStream = new FileInputStream(file);

InputStreamResource inputStreamResource = new InputStreamResource(inputStream);

HttpHeaders headers = new HttpHeaders();

headers.add("Cache-Control", "no-cache, no-store, must-revalidate");

headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));

headers.add("Pragma", "no-cache");

headers.add("Expires", "0");

return ResponseEntity

.ok()

.headers(headers)

.contentLength(file.length())

.contentType(MediaType.parseMediaType("application/octet-stream"))

.body(inputStreamResource);

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值