hyljava

文件下载到本地

package com.shxt.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownLoadServlet extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  this.doPost(request, response);
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  response.setContentType("application/x-msdownload");
  PrintWriter out = response.getWriter();
  response.reset();// 可以加也可以不加
  response.setContentType("application/x-download");
  String filedownload = request.getRealPath("/images")
    + "\\02_开发第一个无状态会话bean.avi";// "想办法找到要提供下载的文件的物理路径+文件名";
  System.out.print(filedownload);
  String filedisplay = "okokok.avi";// "给用户提供的下载文件名";
  filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
  response.addHeader("Content-Disposition", "attachment;filename="
    + filedisplay);
  

  OutputStream outp = null;
  FileInputStream in = null;
  try {
   outp = response.getOutputStream();
   // 你可以指定你的ftp输入流
   in = new FileInputStream(new File(filedownload));

   byte[] b = new byte[1024];
   int i = 0;

   while ((i = in.read(b)) > 0) {
    outp.write(b, 0, i);
   }
   outp.flush();
  } catch (Exception e) {
   System.out.println("Error!");
   e.printStackTrace();
  } finally {
   if (in != null) {
    in.close();
    in = null;
   }
   if (outp != null) {
    outp.close();
    outp = null;
   }
   //out.clear();
   //out = pageContext.pushBody();
  }
 }

}

posted on 2013-11-23 20:51 何云隆 阅读(919) 评论(1)  编辑  收藏 所属分类: Jsp

评论

# re: 文件下载到本地[未登录] 2015-08-11 15:17 1

1  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: