【问题标题】:AngularJS - File Download through AJAXAngularJS - 通过 AJAX 下载文件
【发布时间】:2014-12-23 17:36:41
【问题描述】:

我创建了一个 Angular js 程序,用于从服务器下载文件,代码如下

HTML 代码

<a download="fullList.csv" ng-href="{{ fullListUrl }}" type="button" class="btn btn-success btn-xs exec-batch"  ng-click="exportCSVBulk(batchExec)">
          <span class="glyphicon glyphicon-ok"></span> EXPORT AS CSV
</a>

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 发出请求。只需删除您的 ng-click 属性并依靠浏览器来处理下载。
  • 您是否在服务器端使用 java(Spring 控制器或 Jersey Rest Service 等任何东西...)
  • @BenFoster 我在这里做了一个小改动,这里我需要参数(batchExec)来从 url 获取内容。这也是一个href放在表格行中,因此参数将决定onclick
  • @NidhishKrishnan 是的,我正在使用 Spring Web 服务
  • @AnishAntony 看看我的回答......

标签: java javascript angularjs url spring-mvc


【解决方案1】:

我在通过 Ajax 下载 .pdf、.xls、.xlsx 等文件时遇到了类似的问题。

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

您可以使用jquery.fileDownload - 一个适用于 Ajax 的 jQuery 文件下载插件,具有丰富的文件下载功能。

Demo Working

服务器端

我在服务器端使用 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

【讨论】:

    【解决方案2】:

    我创建了一个更有棱角的解决方案。如果您想与服务器信息同步,服务器必须提供 content-type 和 content-disposition,尽管您可以手动添加类型和下载属性。

     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)
                })
            }
    

    【讨论】:

      猜你喜欢
      • 2016-07-08
      • 2013-05-16
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 2023-03-16
      相关资源
      最近更新 更多