使用io输出流下载:直接上java 代码,
html 界面只需要一个<a href="xxxxx/xxx/xx">下载</a> 地址直接写对应的java 地址就好。
方法一:
@RequestMapping("domload.it")
public void domload(HttpServletResponse response, HttpServletRequest request) throws IOException {
//获得请求文件名
String path = request.getServletContext().getRealPath("/resource/pdf/enquiry.pdf");
System.out.println(path);
//以下载方式打开
response.setHeader("Content-Disposition", "attachment;filename=java.pdf");
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
//写出
ServletOutputStream out = response.getOutputStream();
//定义读取缓冲区
byte buffer[] = new byte[1024];
//定义读取长度
int len = 1024;
//循环读取
while((len = fis.read(buffer))!=-1){
out.write(buffer,0,len);
}
//释放资源
fis.close();
out.flush();
out.close();
}
方法2: @RequestMapping("domload1.it") public void domload1(HttpServletResponse response, HttpServletRequest request) throws IOException { //获得请求文件名 String path = request.getServletContext().getRealPath("/resource/pdf/enquiry.pdf"); System.out.println(path); File file = new File(path); //以下载方式打开 response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(file.getName(),"UTF-8")); //创建刘对象 FileReader reader = new FileReader(file); //写出 PrintWriter out = response.getWriter(); //定义读取缓冲区 char buffer[] = new char[1024]; //定义读取长度 int len = 1024; //循环读取 while((len = reader.read(buffer))!=-1){ out.write(buffer,0,len); } //释放资源 reader.close(); out.flush(); out.close(); }