AngularJS – 通过AJAX下载文件

我创建了一个角度js程序,用于从服务器下载文件,遵循代码

HTML代码

  EXPORT AS CSV  

AngularJS控制器

 $scope.exportCSVBulk=function(){ var page = "../importExportService/exportBulkCSV/"+batchExec.id; $http.get(page).success(function(response) { $scope.fullListUrl = 'data:text/csv;charset=utf-8,' + escape(response); }); } 

这里我要做的是当用户点击EXPORT AS CSV链接时,函数exportCSVBulk触发,并从该函数中设置url值(fullListUrl)。 但这是一个ajax请求,所以当用户点击链接的url时,响应时间会变得有点长,导致url不会正确重定向。 有可能解决这个问题吗? 或者有没有其他方法来解决这个问题?

我通过Ajax下载了.pdf,.xls,.xlsx等文件的类似问题。

事实上,我们无法通过Ajax下载文件,即使我想出了一个通过Ajax下载文件的解决方案。

您可以使用jquery.fileDownload – 用于Ajax的jQuery文件下载插件,function丰富的文件下载。

演示工作

服务器端

我在服务器端使用Spring

 @RequestMapping(value = "exportXLS", method = RequestMethod.POST, produces = APP_JSON) @ResponseBody public void getCSV(final HttpServletResponse response, @RequestParam(value = "empId", required = true) final String empId) throws IOException, Exception { final byte[] csv = ExportXLSUtil.getFileBytes(empId); // get the file bytes final OutputStream output = getOutputStream(response); response.setHeader("Content-Disposition", "attachment; filename=documents_" + new DateTime() + ".xls"); response.setContentType(CONTENT_TYPE); response.setContentLength(csv.length); write(output, csv); } 

客户端

在客户端,我使用的是AngularJS

 $downloadXLS = function(id) { $.fileDownload('/user/exportXLS', { httpMethod : "POST", data : { empId : id } }).done(function(e, response) { // success }).fail(function(e, response) { // failure }); } 

下载链接 – jquery.fileDownload.js

我以更有棱角的方式工作。 如果要与服务器信息同步,服务器必须提供内容类型和内容处置,尽管您可以手动添加类型和下载属性。

  vm.export = function () { //PopUps.showLoading() $http.get(Url).then(function (result) { //PopUps.hideLoading() var headers = result.headers() var blob = new Blob([result.data], { type: headers['content-type'] }) var windowUrl = (window.URL || window.webkitURL) var downloadUrl = windowUrl.createObjectURL(blob) var anchor = document.createElement("a") anchor.href = downloadUrl var fileNamePattern = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/ anchor.download = fileNamePattern.exec(headers['content-disposition'])[1] document.body.appendChild(anchor) anchor.click() windowUrl.revokeObjectURL(blob) }) }