文件下载[异步]
2016-03-07 09:31
288 查看
首先在WEB-INF下创建文件夹download,在download文件夹下放入被下载的文件,在HTTP访问时Controller附带上文件名称即可。
例如:…/download?fileName=jQuery.txt
前端JS部分:
后台Controller:
例如:…/download?fileName=jQuery.txt
前端JS部分:
<script type="text/javascript"> $(document).ready(function(){ $("#load").click(function(){ //点击下载按钮时,调用downLoad()方法,访问后台,实现下载 downLoad('${pageContext.request.contextPath }/download/download','jQuery.txt'); }); }); /* JS实现文件下载: 利用jQuary绘制一个隐藏表单 表单里只有一个hidden隐藏域,域的value为文件名 绘制完毕后自动提交,访问后台Controller,实现文件下载 参数: fromAction:要提交的URL路径 fileName:要下载的文件名称 例如:fromAction:'${pageContext.request.contextPath }/download/download' fileName :'jQuery.txt' */ function downLoad(fromAction,fileName) { var form = $("<form>"); //定义一个form表单 form.attr('style', 'display:none'); //在form表单中添加查询参数 form.attr('target', ''); form.attr('method', 'post'); form.attr('action', fromAction+''); var input1 = $('<input>'); input1.attr('type', 'hidden'); input1.attr('name', 'fileName'); input1.attr('value', fileName+''); //将内置表单添加在页面中 $('body').append(form); //将隐藏域添加到表单上 form.append(input1); form.submit(); } </script>
后台Controller:
/** * @author 佳。 * @date 2016年3月7日 * @Description: 文件下载 * @param: @param fileName 文件名称 * @return String 返回值为null * @throws */ @RequestMapping("download") public void download(String fileName, HttpServletRequest request, HttpServletResponse response) { response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;fileName=" + fileName); try { // /WEB-INF/download文件夹的根目录 String path = request.getSession(). getServletContext().getRealPath("/WEB-INF/download"); // 获取相应文件的流 // File.separator(Windows系统为'/') InputStream inputStream = new FileInputStream(new File(path + File.separator + fileName)); OutputStream os = response.getOutputStream(); byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } // 释放资源 os.close(); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
相关文章推荐
- 《超实用的代码片段》
- UVALive 2191 水一发树状数组
- android开发游记:百度地图SDK路线规划和自定义地图UI覆盖物及弹出窗
- 工作日志
- html BOM、DOM
- 【集合框架】JDK1.8源码分析之LinkedHashMap(二)
- 单例模式
- Android布局中 android:layout_gravity="bottom";为何不起作用?
- Ext的DWRProxy应用事例
- java中不能用小数点(.)来做分隔符
- Android--点击EditText的时候弹出软键盘,点击EditText之外空白处软键盘消失
- Android中常用布局单位
- Android中Context的总结及其用法
- 数字图像处理中的4邻接,8邻接与m邻接
- Shortest Path(hdu5636)
- sphinx-2.2.10-1.rhel6.x86_64 rpm包安装的位置
- 安卓开发环境(eclipse)搭建-(win7,32位)
- C++的全局变量,静态全局变量,常全局变量定义与声明
- centos下查看rpm包安装位置
- JMeter小知识点