AngularJS-通过AJAX下载文件
问题内容:
我创建了一个用于从服务器下载文件的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下载.pdf,.xls,.xlsx等文件时,我也遇到了类似的问题。
这是我们无法通过Ajax下载文件的事实,即使我想出了一种通过Ajax这样下载文件的解决方案。
您可以使用 jquery.fileDownload-
用于Ajax的jQuery文件下载插件,具有功能丰富的文件下载功能。
服务器端
我在服务器端使用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
});
}