使用response实现文件的下载

package cn.itcast.request;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.print.attribute.standard.OutputDeviceAssigned;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownFile extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //得到文件的完全路径
  String path=getServletContext().getRealPath("/img/psb.jpg");
  //得到名称  截取字符串
  //找到最后一个斜杠
  int lens=path.lastIndexOf("\\");
  //截取
  String filename=path.substring(lens+1);
  //处理ie中文文件名的问题
  URLEncoder.encode(filename, "utf-8");
  //设置头
  response.setHeader("Content-Disposition", "attachment;filename"+filename);
  //使用输入流来拿到这个文件
  InputStream in=new FileInputStream(path);
  //使用输出流  把文件写到浏览器
  OutputStream out=response.getOutputStream();
  //流对接
  int len=0;
  byte[] b=new byte[1024];
  while((len=in.read(b))!=-1){
   out.write(b,0,len);
  }
  //关闭流
  in.close();

}

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

}

上一篇:[猜你喜欢]冠军“yes,boy!”分享,含竞赛源代


下一篇:[翻译] C++ STL容器参考手册(第一章