前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >JAVA下载文件代码「建议收藏」

JAVA下载文件代码「建议收藏」

作者头像
全栈程序员站长
发布2022-09-08 10:19:31
发布2022-09-08 10:19:31
5310
举报

大家好,又见面了,我是你们的朋友全栈君。

public static HttpServletResponse download(String path, HttpServletResponse response, String fileName) { try { // path是指欲下载的文件的路径。 File file = new File(path); // 取得文件名。 String filename = fileName; if(StringUtils.isEmpty(fileName)){ filename = file.getName(); } // 取得文件的后缀名。 String ext = filename.substring(filename.lastIndexOf(“.”) + 1).toUpperCase();

// 以流的形式下载文件。 InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 设置response的Header response.addHeader(“Content-Disposition”, “attachment;filename=” + new String(filename.getBytes())); response.addHeader(“Content-Length”, “” + file.length()); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType(“application/octet-stream”); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); } return response; }

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/157191.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档