文件的上传和下载 细节

来源:互联网 发布:java hive jdbc 编辑:程序博客网 时间:2024/05/19 06:16
 

//1.获取下载资源
  String path = this.getServletContext().getRealPath("/download/艺术.jpg");
  //path=c:\aad\download\艺术.jpg
  String filename = path.substring(path.lastIndexOf("
\\")+1);
  System.out.println(filename);
            //文件系统资源用左斜杠 如 \

          //互联网的资源用右斜杠 如 /
  //2.通知浏览器以下载方式打开等会儿发送的资源数据
  response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));  //中文文件名要想正确显示,要经过url编码
  
  //3.读取资源数据  FileInputStream 是字节流
  FileInputStream in = new FileInputStream(path);
  byte buffer[] = new byte[1024];
  int len = 0;
  while((len=in.read(buffer))>0){
   //4.发送资源数据给浏览器
   response.getOutputStream().write(buffer,0,len);
  }

  //5.关闭流
  in.close();

原创粉丝点击