step1:
设置头:response.setHeader("content-disposition","attachment;filename="+文件名);
step2:
读取资源路径:String path = this.getServletContext.getRealPath("文件路径");//文件路径是针对于WebRoot目录下的根路径;此方法获取到的是文件的绝对路径
step3:
构建文件输入流:FileInputStream in = new FileInputStream(path);
构建一个缓冲数组:byte[] buf=new byte[1024];
定义一个变量,存储读取到的字节数:int
len = 0;
step4:
构建一个输出流:OutputStream out = response.getOutputStream();
step5:
把读出来的写出到浏览器
while((len= in.read(buf))!=-1){
out.write(buf,0,len);
}
注意:如果要下载的文件名是中文;需要进行URL编码:
String filename = java.net.URLEncoder.encode(文件名,”utf-8“);
step2:
step3:
step4:
step5:
注意:如果要下载的文件名是中文;需要进行URL编码: