文件下载

来源:互联网 发布:网络基础知识培训 编辑:程序博客网 时间:2024/04/30 16:02

界面: index.jsp   <form action="/testdwr/Test" method="post">
                 <input type="submit" value="下载">
               </form>

创建一个serlvet 名称为Test

servlet  名称为Test,代码

 

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

       response.setContentType("text/html");
    try{
   String root = request.getRealPath("//aa");
   File file =new File(root+"//web.txt");
     //设置response的编码方式
       response.setContentType("application/x-msdownload");
       //写明要下载的文件的大小
       response.setContentLength((int)file.length());
       //解决中文乱码
       response.setHeader("Content-Type", "application/vnd.ms-excel");
       response.setHeader("Content-Disposition","attachment;filename=web.txt");       
       FileInputStream fis=new FileInputStream(file);
       BufferedInputStream buff=new BufferedInputStream(fis);

       byte [] b=new byte[1024];//相当于我们的缓存

       long k=0;//该值用于计算当前实际下载了多少字节

       //从response对象中得到输出流,准备下载
       OutputStream myout=response.getOutputStream();
       //开始循环下载
       while(k<file.length()){
           int j=buff.read(b,0,1024);
           k+=j;

           //将b中的数据写到客户端的内存
           myout.write(b,0,j);

       }
       //将写入到客户端的内存的数据,刷新到磁盘
       myout.flush();
       }catch (Exception e) {
            e.printStackTrace();
       }
 }