`
guodongbingtuan
  • 浏览: 40995 次
  • 性别: Icon_minigender_2
  • 来自: 山西
社区版块
存档分类
最新评论

java实现文件下载

阅读更多

/**
    该类使用方法:
    在使用struts框架(或其他框架)时,如果从action转到该servlet,有一点要注意。就是在使action之前如果是用了filter,并且在filter调用了getWriter()方法,那么action跳转到该servlet时,必须是redirect形式,否则会出错。出错信息大致如下:
    java.lang.IllegalStateException: getWriter() has already been called for this re
    sponse。
    
    该类的两个假设:
    1。假使下载的文件名传送到该servlet的名字是“filename”。使用redirect到本servlet时,参数传送可以通过session;
    2。假使要下载的文件在目录“rootpath”下。
    
    **/
    public class DownloadFile extends HttpServlet {
    
     public String getValue(HttpServletRequest request, String name) {
     String value = null;
     value = request.getParameter(name);
     if (value != null)
     return value;
     value = (String) request.getAttribute(name);
     if (value != null)
     return value;
     value = (String) request.getSession().getAttribute(name);
     request.getSession().removeAttribute(name);
     return value;
     }
    
     public void doPost(HttpServletRequest request, HttpServletResponse response) {
     FileInputStream fis = null;
     ServletOutputStream fout = null;
     try {
     String filename = getValue(request, "filename");
     if (filename != null) {
     String oldcharset = request.getCharacterEncoding();
     String showFilename = null;
     if (oldcharset != null) {
     showFilename = new String(filename.getBytes(request
     .getCharacterEncoding()), "ISO_8859_1");
     } else {
     showFilename = new String(filename.getBytes(), "ISO_8859_1");
     }
     String rootpath = getValue(request, "rootpath");   if (rootpath == null) {
     rootpath = getServletContext().getRealPath("/");
     }
     String filepath = rootpath + filename;
     response.reset();
     response.setHeader("Pragma", "No-cache");
     response.setHeader("Cache-Control", "no-cache");
     response.setDateHeader("Expires", 0);
     response.setContentType("application/octet-stream;charset=GBK");
     response.setHeader("Content-disposition",
     "attachment;filename=\"" + showFilename + "\"");
     fis = new FileInputStream(filepath);
     fout = response.getOutputStream();
     int byteRead;
     while ((byteRead = fis.read()) != -1) {
     fout.write(byteRead);
     }
     }
     } catch (Exception e) {
     e.printStackTrace();
     } finally {
     if (fis != null) {
     try {
     fis.close();
     } catch (IOException e) {
     }
     }
     if (fout != null) {
     try {
     fout.close();
     } catch (IOException e) {
     }
     }
     }
     }
    
     public void doGet(HttpServletRequest request, HttpServletResponse response) {
     doPost(request, response);
     }
    } 
 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics