<%--
直接在JSP页面中进行文件下载的代码(改 Servlet 或者
JavaBean 的话自己改吧), 支持中文附件名(做了转内码处理). 事实上只要向
out 输出字节就被认为是附件内容, 不一定非要从文件读取原始数据, 从数据
库中读取也可以的.
需传三个参数 newname,name,path
--%>
<%@ page contentType=" text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ page import="java.io.*,java.util.*,java.text.*"%>

<%!//If returns true, then should return a 304 (HTTP_NOT_MODIFIED)
public static boolean checkFor304(HttpServletRequest req, File file) {
// We'll do some handling for CONDITIONAL GET (and return a 304)
// If the client has set the following headers, do not try for a 304.
// pragma: no-cache
// cache-control: no-cache
if ("no-cache".equalsIgnoreCase(req.getHeader("Pragma"))
|| "no-cache".equalsIgnoreCase(req.getHeader("cache-control"))) {
// Wants specifically a fresh copy
} else {
// HTTP 1.1 ETags go first
String thisTag = Long.toString(file.lastModified());
String eTag = req.getHeader("If-None-Match");
if (eTag != null) {
if (eTag.equals(thisTag)) {
return true;
}
}
// Next, try if-modified-since
DateFormat rfcDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
Date lastModified = new Date(file.lastModified());
try {
long ifModifiedSince = req.getDateHeader("If-Modified-Since");
// log.info("ifModifiedSince:"+ifModifiedSince);
if (ifModifiedSince != -1) {
long lastModifiedTime = lastModified.getTime();
// log.info("lastModifiedTime:" + lastModifiedTime);
if (lastModifiedTime <= ifModifiedSince) {
return true;
}
} else {
try {
String s = req.getHeader(" If-Modified-Since ");
if (s != null) {
Date ifModifiedSinceDate = rfcDateFormat.parse(s);
// log.info("ifModifiedSinceDate:" + ifModifiedSinceDate);
if (lastModified.before(ifModifiedSinceDate)) {
return true;
}
}
} catch (ParseException e) {
// log.warn(e.getLocalizedMessage(), e);
}
}
} catch (IllegalArgumentException e) {
// Illegal date/time header format.
// We fail quietly, and return false.
// FIXME: Should really move to ETags.
}
}
return false;
}%>
<%
String fileName="AppMappingTemplate.xlsx";
// String filePath=(String)request.getAttribute("filepath");
//获取模板文件所在路径
String filePath = request.getSession().getServletContext().getRealPath("/");
filePath += "pages//xflow//AppMappingTemplate.xlsx";

System.out.println("filepath:" + filePath);
boolean isInline = false; // 是否允许直接在浏览器内打开(如果浏览器能够预览此文件内容,
// 那么文件将被打开, 否则会提示下载)
// 清空缓冲区, 防止页面中的空行, 空格添加到要下载的文件内容中去
// 如果不清空的话在调用 response.reset() 的时候 Tomcat 会报错
// java.lang.IllegalStateException: getOutputStream() has already been called for
// this response,
out.clear();
// {{{ BEA Weblogic 必读
// 修正 Bea Weblogic 出现 "getOutputStream() has already been called for this response"错误的问题
// 关于文件下载时采用文件流输出的方式处理:
// 加上response.reset(),并且所有的%>后面不要换行,包括最后一个;
// 因为Application Server在处理编译jsp时对于%>和<%之间的内容一般是原样输出,而且默认是PrintWriter,
// 而你却要进行流输出:ServletOutputStream,这样做相当于试图在Servlet中使用两种输出机制,
// 就会发生:getOutputStream() has already been called for this response的错误
// 详细请见《More Java Pitfill》一书的第二部分 Web层Item 33:试图在Servlet中使用两种输出机制 270
// 而且如果有换行,对于文本文件没有什么问题,但是对于其它格式,比如AutoCAD、Word、Excel等文件
// 下载下来的文件中就会多出一些换行符0x0d和0x0a,这样可能导致某些格式的文件无法打开,有些也可以正常打开。
// 同时这种方式也能清空缓冲区, 防止页面中的空行等输出到下载内容里去
response.reset();
// }}}
try {
java.io.File f = new java.io.File(filePath);
if (!f.exists()) {
System.out.println("The file is not exist!");
return;
}
if (f.exists() && f.canRead()) {
// 我们要检查客户端的缓存中是否已经有了此文件的最新版本, 这时候就告诉
// 客户端无需重新下载了, 当然如果不想检查也没有关系
if (checkFor304(request, f)) {
// 客户端已经有了最新版本, 返回 304
response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
// 从服务器的配置来读取文件的 contentType 并设置此contentType, 不推荐设置为
// application/x-download, 因为有时候我们的客户可能会希望在浏览器里直接打开,
// 如 Excel 报表, 而且 application/x-download 也不是一个标准的 mime type,
// 似乎 FireFox 就不认识这种格式的 mime type
String mimetype = null;
mimetype = application.getMimeType(filePath);
if (mimetype == null) {
mimetype = "application/octet-stream;charset=UTF-8";
}
response.setContentType(mimetype);
// IE 的话就只能用 IE 才认识的头才能下载 HTML 文件, 否则 IE 必定要打开此文件!
String ua = request.getHeader("User-Agent"); // 获取终端类型
if (ua == null)
ua = "User-Agent:Mozilla/4.0(compatible; MSIE 6.0;)";
boolean isIE = ua.toLowerCase().indexOf("msie") != -1; // 是否为 IE
if (isIE && !isInline) {
mimetype = "application/x-msdownload";
}
// 下面我们将设法让客户端保存文件的时候显示正确的文件名, 具体就是将文件名
// 转换为 ISO8859-1 编码
String downFileName = new String(f.getName().getBytes(),"UTF-8");
String inlineType = isInline ? "inline" : "attachment"; // 是否内联附件
response.setHeader("Content-Disposition", inlineType+";filename=\""+fileName+"\"");
response.setContentLength((int) f.length()); // 设置下载内容大小
byte[] buffer = new byte[4096]; // 缓冲区
BufferedOutputStream output = null;
BufferedInputStream input = null;
try {
output = new BufferedOutputStream(response.getOutputStream());
input = new BufferedInputStream(new FileInputStream(f));
int n = (-1);
while ((n = input.read(buffer, 0, 4096)) > -1) {
output.write(buffer, 0, n);
}
response.flushBuffer();
} catch (Exception e) {
} // 用户可能取消了下载
finally {
if (input != null)
input.close();
if (output != null)
output.close();
}
}
return;
} catch (Exception ex) {
ex.printStackTrace();
}
// 如果下载失败了就告诉用户此文件不存在
response.sendError(404);
%>

download下载excel模板的代码的更多相关文章

  1. 下载excel模板,导入数据时需要用到

    页面代码: <form id="form1" enctype="multipart/form-data"> <div style=" ...

  2. java的poi技术下载Excel模板上传Excel读取Excel中内容(SSM框架)

    使用到的jar包 JSP: client.jsp <%@ page language="java" contentType="text/html; charset= ...

  3. vue Excel导入,下载Excel模板,导出Excel

    vue  Excel导入,下载Excel模板,导出Excel vue  Excel导入,下载Excel模板 <template> <div style="display: ...

  4. java 下载Excel模板

    前端: JSP: <div id="insertBtn" class="MyCssBtn leftBtn" onclick="download( ...

  5. java下载Excel模板(工具类)

    一次文件下载记录 一次不成熟的文件下载操作记录,希望能对需要的人有所帮助. 1.前端代码 $("#downloadModel").click(function(){ var mod ...

  6. poi下载excel模板

    /** * 下载模板 * @param tplName * @param returnName * @param response * @param request * @throws Excepti ...

  7. C# 中从程序中下载Excel模板

    方法一: #region 下载模板 /// <summary> /// 下载模板 /// </summary> /// <param name="sender& ...

  8. html下载excel模板

    只需要href等于模板存放的路径即可 <a href="../../TempLate/Attitude.xlsx" class="easyui-linkbutton ...

  9. 2019.06.05 ABAP EXCEL 操作类代码 OLE方式(模板下载,excel上传,内表下载)

    一般使用标准的excel导入方法9999行,修改了标准的excel导入FM 整合出类:excel的 模板下载,excel上传,ALV内表下载功能. 在项目一开始可以SE24创建一个类来供整体开发使用, ...

随机推荐

  1. hdu_5813_Elegant Construction(xjb搞)

    题目链接:hdu_5813_Elegant Construction 题意: 给你n个点,每个点要可以到达ai个点,可以直接可以间接,不能有环,问是否可行,如果可行就任选一种方式连接,并输出连接的边数 ...

  2. CABasicAnimation 几种停止的回调

    一.编写一个简单的动画,使一个UIview从屏幕的左上角移动到左下角,间隔时间3S // // ViewController.m // CAAnimationTest // // Created by ...

  3. ActiveMQ in Action(4) - Security

    关键字: activemq 2.4 Security    ActiveMQ支持可插拔的安全机制,用以在不同的provider之间切换.2.4.1 Simple Authentication Plug ...

  4. Worker+MQ解惑

    用Worker来保证数据的一致性,再加上MQ来便于水平扩展,也提升了Worker的效率.这就是传说中的Worker+MQ,又叫做可靠消息方式.另外,将任务的查询和执行分工,形成父子任务,达到真正的分布 ...

  5. MvcPager

    站点网址:http://www.webdiyer.com/mvcpager/ 控制台命令:Install-Package Webdiyer.MvcPager

  6. 可写的计算监控(Writable computed observables)

    新手可忽略此小节,可写依赖监控属性真的是太advanced了,而且大部分情况下都用不到. 一般情况下,计算监控的值是通过其他监控属性的值计算出来的,因此它是只读的.这个看似很奇怪,我们有什么办法可以让 ...

  7. iOS开发之 用第三方类库实现ScrollView

    转自:http://www.cnblogs.com/qianLL/p/5369127.html   在github上面有很多的第三方类库,大大节约了大家的开发时间 下载地址:https://githu ...

  8. windows任务计划程序路径设置

    用任务计划启动程序,特别是脚本,比如我要启动python脚本,其中有一句是这么写的 BasePath = removeLastSlash(os.path.abspath("..\\..\\& ...

  9. JQuery_图片未加载!

    JQuery_图片未加载! <html> <head> <script type="text/javascript" src="/jquer ...

  10. yaf for ubuntu安装

    一.安装yaf需要的扩展 apt-get install perl-modules apt-get install libpcrecpp0 apt-get install libpcre3 libpc ...