三叶草 发表于 2021-10-25 12:15:37

用JSP下载word文件(不会直接用IE打开)

<%@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;
      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;
%>

https://www.uoften.com/program/jsp/20180413/47246.html
页: [1]
查看完整版本: 用JSP下载word文件(不会直接用IE打开)