JSP文件下載

普偏JSP代有中文的文件下載會出現亂碼現象,最近整理網上的例子,解決發放如下

下載連接頁 

<% String fname ="文件.rar%>
<%  String   tf=new   String   (fname.getBytes("utf-8"),"GBK");%> 
<a target="_blank" href="download.jsp?filename=<%=URLEncoder.encode(fname,"GBK")%>">下載</a>

下載頁面:

<%
   out.clear();
   out = pageContext.pushBody();
   java.io.BufferedInputStream bis = null;
   java.io.BufferedOutputStream bos = null;
   OutputStream os = null;
   try {
    String filename = request.getParameter("filename");
    filename = new String(filename.getBytes("iso8859-1"), "gb2312");
    response.setContentType("application/x-msdownload");
    response.setHeader("Content-disposition",
      "attachment; filename="
        + new String(filename.getBytes("gb2312"),
          "iso8859-1"));
    bis = new java.io.BufferedInputStream(
      new java.io.FileInputStream(config.getServletContext()
        .getRealPath(filename)));
    os = response.getOutputStream();
    bos = new java.io.BufferedOutputStream(os);
    byte[] buff = new byte[2048];
    int bytesRead;
    while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
     bos.write(buff, 0, bytesRead);
    }
   } catch (Exception e) {
    e.printStackTrace();
   } finally {
    if (bis != null)
     bis.close();
    if (bos != null)
     bos.close();
    if (os != null)
     os.close();
   }
  %>

這段代碼解決了下載報錯的問題,必須添加上去

out.clear();
   out = pageContext.pushBody();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章