之前的思路一直是弹出一个框问用户想要存放文件的位置,然后我再生成个文件放到那。然而我这个想法并没有成功。
点击链接来下载文件的方式很简便,后台把文件流输出来,通过浏览器实现下载功能,包括询问位置与文件存放,大多数浏览器会配置一个固定位置,不一定每次都问。
前端就非常简单了,一个<a>标签,href=“后台方法地址”,如果你的需求不能直接用超链接方式,可以在js里写 window.location.href =“后台方法地址”。
这样跳转到后台方法后
String filePath = this.getClass().getClassLoader().getResource("").toURI().getPath() + "/exportPdf.pdf"; //文件在项目中的路径 File outfile = new File(filePath); String filename = outfile.getName();// 获取文件名称 InputStream fis = new BufferedInputStream(new FileInputStream( filePath)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); //读取文件流 fis.close(); response.reset(); //重置结果集 response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"), "iso8859-1")); //返回头 文件名 response.addHeader("Content-Length", "" + outfile.length()); //返回头 文件大小 response.setContentType("application/octet-stream"); //设置数据种类 //获取返回体输出权 OutputStream os = new BufferedOutputStream(response.getOutputStream()); os.write(buffer); // 输出文件 os.flush(); os.close();
浏览器会直接识别这种形式的文件输出,弹出对话框。
注意此方法一定要用链接方式调后台,使用ajax和XMLHttpRequest方式都是不行的,这样返回的文件流会返回到方法的回调函数中,当然如果你想在js中获取文件,这样也行。
原文:http://my.oschina.net/u/2462382/blog/517135