免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1292 | 回复: 0
打印 上一主题 下一主题

servlet实现文件下载功能---Head First Series [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-09-04 17:32 |只看该作者 |倒序浏览
PART 1:问题症状
在项目中通过JSP形式下载文件
downloadFile.jsp
[email=%@page]%@page[/email]
pageEncoding="gb2312"%>
[email=%@page]%@page[/email]
contentType="text/html;charset=gb2312"%>

String realpath = request.getRealPath("/WEB-INF/uploaded_files/helpAttach");
String downloadUrl=realpath + "/" + attachfileName;
String encodeUrl = new String(
   downloadUrl.getBytes("UTF-8"), "UTF-8");
   
try {
  if (attachfileName !=null) {
    //String subFileName=attachfileName.substring(attachfileName.lastIndexOf("."));
    //String downloadFileName="onlineHelp" + subFileName;

    File file=new File(encodeUrl);
    if (file.exists()) {
      FileInputStream  fin=null;
      OutputStream fout=null;
      try {
      fin=new FileInputStream(file);
      byte[] b=new byte[(int) file.length()];
      fin.read(b);
                     //System.out.println(new String(attachfileName.getBytes("GB2312"),"iso8859-1"));
                     //Charset test = Charset.defaultCharset();
               //String serverCharset = test.displayName();
                     //System.out.println("serverCharset:" + serverCharset);
                     response.setContentType("application/x-msdownload");
                     response.setHeader("Content-disposition","attachment; filename=" + new String(attachfileName.getBytes("GB2312"),"iso8859-1"));
      
   
      fout = response.getOutputStream();
      fout.write(b);
     } catch (IOException ex) {
      ex.printStackTrace();
     } finally {
      if (fin != null) {
       fin.close();
      }
      if (fout != null) {
       fout.close();
      }
     }
   }
  }
} catch (Exception e) {
  e.printStackTrace();
} finally {
}
%>

虽然可以实现具体的文件下载功能,但是程序老报如下警告信息:
java.lang.IllegalStateException: WEB3024: getOutputStream() has already been called for this response
at org.apache.catalina.connector.ResponseBase.getWriter(ResponseBase.java:880)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:165)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:184)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:176)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:187)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext
......

--------------------------------------------------------------------------------
PART 2:如何解决
经过深入的比较和分析,最终使用了Servlet的方法成功的解决了该问题,希望对大家多有所帮助!(注意:其中涉及到一些很简单的业务,多余部分的代码请大家自己剔除.)
STEP 1:修改web.xml文件,添加如下内容:


  downloadServlet
  
   com.emerson.pts.common.DownloadServlet
  
  
   contentType
   application/x-msdownload
  
  
   enc
   utf-8
  
  
   fileRoot
   
    /WEB-INF/uploaded_files/helpAttach
   
  




  downloadServlet
  /servlet/downloadServlet


STEP 2:编写Servlet类
DownloadServlet.java

package com.emerson.pts.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.emerson.pts.sys.onlineHelp.service.OnlineHelpBean;
import com.emerson.pts.sys.onlineHelp.service.OnlineHelpService;
import com.emerson.pts.util.HibernateSessionFactory;
public class DownloadServlet extends HttpServlet {
private String contentType = "application/x-msdownload";
private String enc = "utf-8";
private String fileRoot = "";
/**
  * 初始化contentType,enc,fileRoot
  */
public void init(ServletConfig config) throws ServletException {
  String tempStr = config.getInitParameter("contentType");
  if (tempStr != null && !tempStr.equals("")) {
   contentType = tempStr;
  }
  tempStr = config.getInitParameter("enc");
  if (tempStr != null && !tempStr.equals("")) {
   enc = tempStr;
  }
  tempStr = config.getInitParameter("fileRoot");
  if (tempStr != null && !tempStr.equals("")) {
   fileRoot = tempStr;
  }
}

protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  String helpIdToString = request.getParameter("helpId");
  try {
   OnlineHelpService helpService = new OnlineHelpService();
   OnlineHelpBean helpItem = helpService
     .getOnlineHelpItemInfo(helpIdToString);
   String initFileName = helpItem.getHelpAttachFileName();
   //System.out.println(initFileName);
   String fullFilePath = request.getSession().getServletContext()
     .getRealPath(fileRoot + "/" + initFileName);
   // System.out.println("************:" + fullFilePath);
   /* 读取文件 */
   File file = new File(fullFilePath);
   /* 如果文件存在 */
   if (file.exists()) {
    String filename = URLEncoder.encode(file.getName(), enc);
    response.reset();
    response.setContentType(contentType);
    response.addHeader("Content-Disposition",
      "attachment; filename=\"" + filename + "\"");
    int fileLength = (int) file.length();
    response.setContentLength(fileLength);
    /* 如果文件长度大于0 */
    if (fileLength != 0) {
     /* 创建输入流 */
     InputStream inStream = new FileInputStream(file);
     byte[] buf = new byte[4096];
     /* 创建输出流 */
     ServletOutputStream servletOS = response.getOutputStream();
     int readLength;
     while (((readLength = inStream.read(buf)) != -1)) {
      servletOS.write(buf, 0, readLength);
     }
     inStream.close();
     servletOS.flush();
     servletOS.close();
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
  }
}
}

STEP 3:在JSP页面上使用该Servlet下载该文件
......
/servlet/downloadServlet?helpId=">
......

At last,Congratulations to you!



本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/47272/showart_374177.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP