Springboot实现浏览器下载文件

 2023-09-05 阅读 51 评论 0

摘要:public void getUnbondFile(HttpServletResponse response) throws FileNotFoundException, UnsupportedEncodingException {String fileName = "批量解绑设备模板.xlsx";File file = ResourceUtils.getFile("classpath:static/unbondFile.xlsx");res
public void getUnbondFile(HttpServletResponse response) throws FileNotFoundException, UnsupportedEncodingException {String fileName = "批量解绑设备模板.xlsx";File file = ResourceUtils.getFile("classpath:static/unbondFile.xlsx");response.setContentType("application/force-download");response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("gb2312"),"ISO8859-1"));byte[] buffer = new byte[1024];FileInputStream fis = null;BufferedInputStream bis = null;OutputStream outputStream = null;try {bis = new BufferedInputStream(new FileInputStream(file));outputStream = response.getOutputStream();int i = bis.read(buffer);while (i != -1) {outputStream.write(buffer, 0, i);i = bis.read(buffer);}outputStream.flush();} catch (Exception e) {e.printStackTrace();} finally {if (outputStream != null) {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}if (bis != null) {try {bis.close();} catch (IOException e) {e.printStackTrace();}}if (fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}

涉及到java读取Resources路径下的文件,和如何让浏览器下载文件,以及下载文件名的编码格式。

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://808629.com/17.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 86后生记录生活 Inc. 保留所有权利。

底部版权信息