用JSP下载word文件(不会直接用IE打开)
发布时间:2006-10-14 3:02:40   收集提供:gaoqian

<%@page import="java.util.*"%>
<%@page import="java.io.*"%>
<%@page import="java.net.*"%>
<%
    String filename = "";
    if (request.getParameter("file") != null) {
        filename =     request.getParameter("file");
    }
    response.setContentType("application/msword");
    response.setHeader("Content-disposition","attachment; filename="+filename);
    
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        bis = new BufferedInputStream(new FileInputStream(getServletContext().getRealPath("" + filename)));
        bos = new BufferedOutputStream(response.getOutputStream());

        byte[] buff = new byte[2048];
        int bytesRead;

        while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff,0,bytesRead);
        }

    } catch(final IOException e) {
        System.out.println ( "出现IOException." + e );
    } finally {
        if (bis != null)
            bis.close();
        if (bos != null)
            bos.close();
    }
    return;
%>

 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50