JavaWeb文件下载功能实例代码
时间:2020-11-19 17:30:56|栏目:JAVA代码|点击: 次
在工作中遇到的一个下载文件的功能,自己将其抽取出来,代码简单,希望能帮到大家,好了,话不多说,上代码!
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();
}
}
}
上一篇:Tomcat 多端口 多应用
栏 目:JAVA代码
本文标题:JavaWeb文件下载功能实例代码
本文地址:http://www.codeinn.net/misctech/24144.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




