日期:2014-05-16  浏览次数:20327 次

jsp、java下载附件
传入此jsp中的参数均已URLDencoder过。<%@page import="java.net.URLEncoder"%>
<%@page import="java.io.BufferedOutputStream"%>
<%@ page contentType="text/html;charset=utf-8"  pageEncoding="utf-8"%>
<%
boolean isError = false;
String errorMsg = "";
response.reset();//可以加也可以不加
request.setCharacterEncoding("UTF-8");
String folder = "news";
if(request.getParameter("folder")!=null){
folder = "upload/"+(String)request.getParameter("folder");
}
String newname = request.getParameter("newname");
// 是否允许直接在浏览器内打开
   boolean isInline = false ;
    out.clear();
    response.reset();
    String filePath = request.getRealPath("/"+folder)+"/" +newname;
    java.io.BufferedOutputStream output = null ;
    java.io.BufferedInputStream input = null ;
try {
java.io.File f  = new  java.io.File(filePath);
if(f.exists() && f.canRead()){
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";
            }
            response.setContentType(mimetype);
          // 是否内联附件
            String inlineType = isInline?"inline":"attachment";
           response.setHeader("Content-Disposition" , inlineType + ";filename=" + filename);
          // 设置下载内容大小
            response.setContentLength((int)f.length());
        // 缓冲区
            byte[] buffer = new byte[ 4096 ];
            output = new java.io.BufferedOutputStream(response.getOutputStream());
                input = new java.io.BufferedInputStream(new java.io.FileInputStream(f));
                int n = (-1);
                while((n=input.read(buffer,0,4096))>-1){
                output.write(buffer,0,n);
  &n