java文件下载

<%@ page import="java.io.*"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/jsp/include/common.jsp"%>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%
try{
    String hostPath = request.getContextPath();
    {
        InputStream is = null;
        OutputStream os = null;
        java.io.File file = null;
        try {
            //接到的页面传来的文件名(真实名称)
            String filename=request.getParameter("filename");
            //String filename="我爱中华";
            //System.out.println("---------filename1-------:"+filename);
            //filename = new String(filename.getBytes("iso8859-1"), "utf-8");
            //String filename = new String(request.getParameter("filename"));
            //System.out.println("---------filename2-------:"+filename);
            //String url = new String(request.getParameter("fileurl").getBytes("iso8859-1"), "UTF-8");
            String url = new String(request.getParameter("fileurl"));
            //文档基本路径
            String path2 = application.getRealPath(url);

            file = new File(path2);
            if (file != null && file.exists() && file.isFile()) {
        long filelength = file.length();
        is = new FileInputStream(file);
        os = response.getOutputStream();
        //设置输出的格式
        response.reset();
        response.setContentType("application/x-msdownload");
        response.setContentLength((int) filelength);
        response.addHeader("Content-Disposition",
                "attachment; filename=\""
                + new String(filename
                .getBytes("GBK"),//只有GBK才可以
                "iso8859-1") + "\"");
                //"attachment; filename=\""
                //+ filename
                //+ "\"");
        //循环取出流中的数据
        byte[] b = new byte[4096];
        int len;
        while ((len = is.read(b)) > 0) {
            os.write(b, 0, len);
        }
            } else {
        out.println("<script>");
        out.println(" alert('The file is not exist!');");
        out.println(" history.go(-1);");
        out.println("</script>");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
        is.close();
            }
            if (os != null) {
        os.close();
            }
        }
    }
}catch(Exception e){
    e.printStackTrace();
}
%>

 

posted @ 2013-08-01 08:42  smail2013  阅读(266)  评论(0编辑  收藏  举报