从服务端到浏览器的简单处理, 仅供参考
Java 定义一个export的功能函数,以下为关键代码(接口中的一部分处理逻辑):
@Override public byte[] export(String startdate, String enddate, Integer type, String name, HttpServletResponse response) { // other logic omitted here ... // set response args,it used for open download response.reset(); response.setContentType("application/vnd.ms-excel;charset=utf-8"); try { response.setHeader("Content-Disposition", "attachment;filename=" + new String((name+ ".xls").getBytes(), "iso-8859-1")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } ByteArrayOutputStream output = new ByteArrayOutputStream(); try { workList.write(output); // write } catch (IOException e) { e.printStackTrace(); } return output.toByteArray(); }指令如下:
angular.module('yourNgApp') .directive('sysExport', function ($http, $document) { return { templateUrl: "app/system/export/export.directive.html", restrict: 'EA', replace: true, scope: { item: '=' }, link: function (scope, element) { // 访问请求的函数 function getExport(postData) { // 拼出自己的url var url = '/api/course/export?startdate=' + postData.startdate + '&enddate=' + postData.enddate + '&type=' + postData.type + '&name=' + postData.name; // 注意下面的responseType 一定要有哦! var finalPostData = { url: url, method: 'POST', responseType: "arraybuffer", headers: {'Content-type': 'application/json'} }; $http(finalPostData) .success(function (data) { var blob, fileName, blobArgs; blobArgs = {type: 'application/vnd.ms-excel application/x-excel'}; blob = new Blob([data], blobArgs); var a = $document[0].createElement('a'); a.download = postData.name + '.xls'; a.href = URL.createObjectURL(blob); a.click(); }) .error(function (e) { console.log(e); }); } element.on('click', function () { getExport(scope.item); }); } }; }); 至此可实现通过指令的点击事件来下载excel格式了。因为导出功能多用于后台管理,适用性不是很普遍,所以兼容问题可协商,所以前台使用了Blob对象。为了节约服务器资源可通过此种方式通过点击来下载,而不是将导出的文件单独存放到服务器上通过返回excel所在的url地址来进行下载。2)方式2:直接通过a链接访问,[兼容性好]
示例:
<a href="/api/course/export?startdate={{cl.startdate}}&enddate={{cl.enddate}}&type={{cl.type}}&name={{cl.name}}" class="btn btn-success">导出</a>上面前端用到的都是一些H5高级API 适用性不是很高, 但也临时解决了一些问题,只作为尝试 :) 通过a链接的方式请求, 直接在服务器端完成文件的操作,点击后直接下载,兼容良好,但不适合大文件的传输下载。