JavaWeb文件下载功能实例代码
更新时间:2016年06月29日 10:16:03 作者:sennhai
这篇文章主要为大家详细介绍了JavaWeb文件下载功能实例代码,代码简单实用,感兴趣的小伙伴们可以参考一下
在工作中遇到的一个下载文件的功能,自己将其抽取出来,代码简单,希望能帮到大家,好了,话不多说,上代码!
public void downloadFile(File file, String downName, HttpServletRequest request, HttpServletResponse response) { OutputStream out = null; FileInputStream fin = null; BufferedInputStream bin = null; try { if (file.exists()) { String finalFileName = null; String agent = request.getHeader("User-Agent"); boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1); if (isMSIE) { finalFileName = URLEncoder.encode(downName, "UTF8"); } else { finalFileName = new String(downName.getBytes("UTF-8"), "ISO-8859-1"); } response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=".concat(finalFileName)); out = response.getOutputStream(); fin = new FileInputStream(file); bin = new BufferedInputStream(fin); for (int data = bin.read(); data > -1; data = bin.read()) { out.write(data); } } else { } } catch (Exception e) { e.printStackTrace(); } finally { try { if (bin != null) bin.close(); if (fin != null) fin.close(); if (out != null) out.close(); } catch (Exception e2) { e2.printStackTrace(); } } }
以上就是本文JavaWeb文件下载的代码,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
spring整合JMS实现同步收发消息(基于ActiveMQ的实现)
本篇文章主要介绍了spring整合JMS实现同步收发消息(基于ActiveMQ的实现),具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-10-10springcloud中RabbitMQ死信队列与延迟交换机实现方法
死信队列是消息队列中非常重要的概念,同时我们需要业务场景中都需要延迟发送的概念,比如12306中的30分钟后未支付订单取消,那么本期,我们就来讲解死信队列,以及如何通过延迟交换机来实现延迟发送的需求,感兴趣的朋友一起看看吧2022-05-05
最新评论