javaweb jsp页面中实现文件下载
来源:互联网 发布:北京网络经理薪资 编辑:程序博客网 时间:2024/06/04 19:41
在jsp中有一个a标签 ,当用户点击a标签的时候下载文件。
我们采用href属性直接指向一个服务器地址,只要链接的文件存在,就会给出弹出保存对话框.
点击a标签 先执行onclick事件,再请求href中指向的地址。
前端jsp:
<a href="#" onclick="javascript:downloadtest('${app.id}')" id="pluginurl" style="color: #83AFE2;text-decoration:underline;"></a>
然后在js中:
function downloadtest(id){
var url = "<%=request.getContextPath()%>/app/download" + "/" + id;
$("#pluginurl").attr("href",url);
}
后台java代码: 我的是springmvc
/** * 下载文件 * @param id appid * @param response */@RequestMapping(value="/download/{id}")public void download(@PathVariable String id, HttpServletResponse response){String filepath = "";Result result = appService.getAppById(id);App app = (App) result.getMap().get("app");if(app == null){return;}filepath = app.getUrl();File file = new File(filepath);InputStream inputStream = null;OutputStream outputStream = null;byte[] b= new byte[1024];int len = 0;try {inputStream = new FileInputStream(file);outputStream = response.getOutputStream();response.setContentType("application/force-download");String filename = file.getName();filename = filename.substring(36, filename.length());response.addHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));response.setContentLength( (int) file.length( ) );while((len = inputStream.read(b)) != -1){outputStream.write(b, 0, len);}} catch (Exception e) {e.printStackTrace();}finally{if(inputStream != null){try {inputStream.close();inputStream = null;} catch (IOException e) {e.printStackTrace();}}if(outputStream != null){try {outputStream.close();outputStream = null;} catch (IOException e) {e.printStackTrace();}}}}
注意:response.addHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
这句必须将文件名字编码一下,不然对于中文名字可能会出现乱码,或者不显示中文名只有后缀。
代码分析,我项目里面先通过id查找对应的bean对象,然后这个对象里面url保存的是服务器端文件系统中的地址比如:“C://download/test.txt”
因为本项目中文件上传的时候保存在服务器文件系统中的,而数据库中保存服务器文件系统地址就可以了。
最主要的是将文件写到输出流中,而且要设置response.addHeader 和 response.setContentLength属性。
- javaweb jsp页面中实现文件下载
- Jsp中实现文件下载
- jsp中实现文件下载
- jsp页面实现点击下载保存文件
- javaWeb实现文件下载
- jsp页面 下载文件
- Jsp中实现文件上传与下载
- jsp中实现普通文件下载
- 如何用jsp中实现文件下载
- javaWeb 实现上传+下载 文件
- JavaWeb实现文件上传 / 下载
- javaWeb方法实现文件下载
- javaWeb 实现上传+下载 文件
- jsp页面下载txt文件
- down_file.jsp 文件下载页面
- jsp页面下载html文件
- jsp页面链接下载文件
- JSP实现文件下载
- PHP如何调用类
- hadoop2.2.0-错误- ERROR security.UserGroupInformation: PriviledgedActionException as:s011 (auth:SIMPLE
- C# asp.net MVC 权限设计(续)
- Android使用Application总结
- android 通讯录的查看和添加
- javaweb jsp页面中实现文件下载
- .net 调用webservice 总结
- 关于std::string.length() std::string.size()
- 安装subclipse, MyEclipse10 SVN插件,link方法
- 如何解决c++中循环包含头文件的问题
- 黑马程序员_毕向东_Java基础视频教程学习笔记(七)
- MyEclipse下开发Web Service(Axis)
- 如何用git创建一个项目
- Jeecg 初级入门