以前的思路一直是弹出一个框问用户想要存放文件的位置,而后我再生成个文件放到那。然而我这个想法并无成功。
前端
点击连接来下载文件的方式很简便,后台把文件流输出来,经过浏览器实现下载功能,包括询问位置与文件存放,大多数浏览器会配置一个固定位置,不必定每次都问。java
前端就很是简单了,一个<a>标签,href=“后台方法地址”,若是你的需求不能直接用超连接方式,能够在js里写 window.location.href =“后台方法地址”。ajax
这样跳转到后台方法后浏览器
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();
浏览器会直接识别这种形式的文件输出,弹出对话框。app
注意此方法必定要用连接方式调后台,使用ajax和XMLHttpRequest方式都是不行的,这样返回的文件流会返回到方法的回调函数中,固然若是你想在js中获取文件,这样也行。函数