Java Web项目中经常要用到的文件下载功能。
从前端到后台实现为jsp+java
后台实现思路
1 得到文件在服务器上存储的绝对路径
2 将文件读入文件流
3 判断浏览器代理并设置不同的编码格式
4 设置响应头
5 循环取出流中的数据
6 关闭流
代码
jsp代码
<button id="download">点击下载</button><script>$("#download").click(function(){location.href=downloadFile.do//此处为后台在struts。xml中配置的方法名})</script>
/** * 下载文件 */ public void downloadFile(){
//根据条件得到文件路径 String fileurl="/01/demand/upload/20160316/下载.docx"; System.out.println("===========文件路径==========="+url); //将文件读入文件流 InputStream inStream = new FileInputStream(fileurl); //获得浏览器代理信息 final String userAgent = super.getRequest().getHeader("USER-AGENT"); //判断浏览器代理并分别设置响应给浏览器的编码格式 String finalFileName = null; if(StringUtils.contains(userAgent, "MSIE")||StringUtils.contains(userAgent,"Trident")){//IE浏览器 finalFileName = URLEncoder.encode(showValue,"UTF8"); System.out.println("IE浏览器"); }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器 finalFileName = new String(showValue.getBytes(), "ISO8859-1"); }else{ finalFileName = URLEncoder.encode(showValue,"UTF8");//其他浏览器 } //设置HTTP响应头 super.getResponse().reset();//重置 响应头 super.getResponse().setContentType("application/x-download");//告知浏览器下载文件,而不是直接打开,浏览器默认为打开 super.getResponse().addHeader("Content-Disposition" ,"attachment;filename=\"" +finalFileName+ "\"");//下载文件的名称 System.out.println(showValue); // 循环取出流中的数据 byte[] b = new byte[1024]; int len; while ((len = inStream.read(b)) > 0){ super.getResponse().getOutputStream().write(b, 0, len); } inStream.close(); super.getResponse().getOutputStream().close(); }catch(Exception e) { e.printStackTrace(); System.out.println("==========出错了!!==========="); } System.out.println("============成功了!!==========="); }
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts> <package name="downloadFile" extends="interceptor-default" namespace="/downloadFile"> <action name="downloadFile" class="downloadFile.java" method="downloadFile"> </action> </package></struts>
本文介绍了在Java Web项目中如何实现文件下载功能,详细阐述了从jsp到java后台的处理流程,包括获取服务器文件路径、读取文件流、设置响应头、处理不同浏览器编码、输出数据以及关闭流的步骤。
1114

被折叠的 条评论
为什么被折叠?



