前言

JQuery Mobile的请求基本上都是通过Ajax来完成的,但是ajax请求只是个“字符型”的请求,即请求的内容是以文本类型存放的,文件的下载是以二进制形式进行的也就是流,ajax是不能返回的,虽然可以读取到返回的response,但只是读取而已,是无法执行的。

解决方案,不用ajax:

使用XHR 全称:XMLHttpRequest

废话不多说直接上代码吧:

1. 前端请求

     function downloadAttachments(attachmentId) {var url = 'http://localhost/KRISADMIN/downloadAttachment';var xhr = new XMLHttpRequest();xhr.open('POST', url);// 也可以使用POST方式,根据接口,也可以写getxhr.responseType = "arraybuffer";// 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑xhr.onload = function () {// 请求完成if (this.status === 200) {// 返回200var blob = new Blob([this.response], {type: "application/octet-stream"});var reader = new FileReader();reader.readAsDataURL(blob);// 转换为base64,可以直接放入a表情hrefreader.onload = function (e) {//手机浏览器 必须这么保存文件才能正确打开,因为当返回的流很//长的时候IE浏览器会报“传递给系统调用的数据区域太小”的错,同时手机浏览器会下载错误的文件if(navigator.msSaveBlob){ // IE 10+ navigator.msSaveBlob(new Blob([blob],{type:'application/octet-stream; charset = utf-8;'}),filename); }else{// 转换完成,创建一个a标签用于下载var a = document.createElement('a');a.download = filename;a.href = e.target.result;$("body").append(a);// 修复firefox中无法触发clicka.click();$(a).remove();  }}}};// 发送ajax请求xhr.send(attachmentId)}

2. 服务器端

我项目是ssh的,用了rest的插件,接口都是restful接口暴露的。接口如下:

@Action(value="/downloadAttachment")
public void  downloadAttachment() throws IOException{ActionContext ctx = ActionContext.getContext();String attachmentId = getRequestBody(ctx);attachmentId=attachmentId.replaceAll("\"", "");WFAttachment wfattachment=workFlowService.findAttachmentByID(Integer.parseInt(attachmentId));fileName=wfattachment.getFileName();HttpServletRequest request = ServletActionContext.getRequest();HttpServletResponse response=ServletActionContext.getResponse();String userAgent = request.getHeader("User-Agent");  if (null != userAgent && -1 != userAgent.indexOf("Firefox")){ //Firefox  fileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");     }else{     fileName = URLEncoder.encode(fileName, "UTF-8"); fileName = fileName.replace("+", "%20");}String extension =fileName.substring(fileName.lastIndexOf(".")+1);String path=wfattachment.getSavePath();String strOldNmme = path +"/"+ attachmentId+"."+extension;//上面代码都是在我项目中获取文件的过程,文件获取到之后才是重点File f = new File(strOldNmme);//导出文件String agent = request.getHeader("User-Agent").toUpperCase();InputStream fis = null;OutputStream os = null;try {fis = new BufferedInputStream(new FileInputStream(f.getPath()));byte[] buffer;buffer = new byte[fis.available()];fis.read(buffer);response.reset();//我注释的这段代码是因为在我系统获取fileName时,已经做过这个操作了,就不需要了判断了直接addHeader就行了,你若果在你系统获取filename是没有做此操作,则需要这段代码进行判断添加/* //由于火狐和其他浏览器显示名称的方式不相同,需要进行不同的编码处理if(agent.indexOf("FIREFOX") != -1){//火狐浏览器response.addHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("GB2312"),"ISO-8859-1"));}else{//其他浏览器response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));}*/response.addHeader("Content-Disposition", "attachment;filename="+ fileName);//设置response编码response.setCharacterEncoding("UTF-8");response.addHeader("Content-Length", "" + f.length());//设置输出文件类型(有很多具体可以看setContentType参数,application/octet-stream就是二进制流)  response.setContentType("application/octet-stream");//获取response输出流os = response.getOutputStream();// 输出文件os.write(buffer);}catch(Exception e){System.out.println(e.getMessage());} finally{//关闭流try {if(fis != null){fis.close();}} catch (IOException e) {System.out.println(e.getMessage());} finally{try {if(os != null){os.flush();}} catch (IOException e) {System.out.println(e.getMessage());} finally{try {if(os != null){os.close();}} catch (IOException e) {System.out.println(e.getMessage());}}}}}

效果图:

有什么不清楚的,留言一起学习

2018/12/12 18:05:42

Jquery Mobile如何下载文件相关推荐

  1. 利用jQuery实现ajax下载文件时进度条

    实现原理:模拟一个虚拟的进度,利用里面子元素的宽度变化来实现进度增长, 关键属性:transition 预览: 进度条 html <div class="lineProgress&qu ...

  2. jQuery Mobile基础

    1.安装 在<head></head>标签里边写入以下内容 jQuery Mobile CDN: 1 <head> 2 <meta charset=" ...

  3. jQuery Mobile 图标无法显示

    对jquery mobile来说,使用data-icon属性配置,可以设置元素的图标.图标没有变成右箭头,而是如下图所示: //已经设置了图标 ,data-icon="home" ...

  4. JQuery Mobile(书籍分类检索)

    1.什么时候使用JQuery mobile 呢? 所有功能性比较强的网站,比如订酒店(如:携程).租车.订票等这样需要有本地APP 界面的网站.就需要使用JQuery mobile 如图:       ...

  5. jquery mobile android浏览器,我们怎样使用jQuery Mobile实现手机新闻浏览器

    大家是否还对这部分知识存在疑问呀,让我来为大家详细解答一下. Mobile项目是jQuery项目下的在方面的又一力作.swift 教程在本文中,笔者将带你一步步更深入学习使用jQuery Mobile ...

  6. jquery mobile android浏览器,使用JQuery Mobile实现手机新闻浏览器

    [IT168 专稿]jQuery Mobile项目是jQuery项目下的在移动开发方面的又一力作,在本文中,笔者将带你一步步更深入学习使用jQuery Mobile框架去实现一个能在android手机 ...

  7. jQuery Mobile框架的简单介绍

    When the world discovered the web, things were unexciting and lifeless. For example, building a simp ...

  8. jQuery Mobile 笔记(1)- jQuery Mobile页面结构

    jQuery Mobile页面解构 jQuery Mobile 的"页面"结构不同于传统的html页面,这样做是为了优化single page application的用户体验. ...

  9. 使用 jQuery Mobile 与 HTML5 开发 Web App (十) —— jQuery Mobile 默认配置与事件基础

    从本文开始,使用 jQuery Mobile 与 HTML5 开发 Web App 系列将 会进入第三部分--jQuery Mobile 事件与方法,这其中将会利用之前所讲述的 jQuery Mobi ...

最新文章

  1. 基于DirectX的游戏引擎-Xworld
  2. grunt使用小记之开篇:grunt概述
  3. jenkins构建触发器定时任务
  4. : Attribute xmlns was already specified for element web-app.
  5. Bootstrap 禁用的按钮
  6. Java21天打卡day18--继承
  7. Googgle guava ImmutableCollections
  8. 磁盘驱动属于计算机的,计算机基本知识(8005)---HDD(硬盘驱动器Hard Disk Drive)
  9. 2020 中国移动的流量套餐
  10. 30岁成功入职京东啦
  11. 感恩中国30年,速速来看甲骨文数据库云大会
  12. Sophus库(Linux下)的安装(模板类.hpp,非模板类.h)
  13. PaddleNLP实战——LIC2021事件抽取任务基线(附代码)
  14. python开发框架大全_最常用Python开源框架有哪些?
  15. 用Kubernetes部署超级账本Fabric的区块链即服务
  16. js获取指定字符后面的字符
  17. 分布式:Docker
  18. qt 动画 顺序 轮播图轮播图
  19. Android内存优化总结实践
  20. 豆瓣FM snap应用

热门文章

  1. SpringBoot之AOP面向切面编程
  2. 第三十四届广东金融科技交流会顺利举行,墨云分享风险验证技术新思路
  3. 测绘专业计算机应该学什么,视频 | 测绘工程有哪些就业方向,什么人适合学习测绘工程专业...
  4. 详解Unity中的Nav Mesh新特性|导航寻路系统 (二)
  5. 相同和相等的区别。。。
  6. 023_接口类,抽象类,多态,鸭子类型,封装
  7. 鸟哥的linux私房菜 NO.1
  8. 2012.4.29~2012.5.1平谷(二)
  9. Revit 2014 发布, Revit 2014 API新功能
  10. 前端使用XLSX导出表格