maa*_*nus 5 javascript iframe download angularjs
下载文件看起来非常简单,有许多工作解决方案.工作直到服务器说401 UNAUTHORIZED.我的要求很自然:
我尝试使用an iframe作为链接的目标,并希望在出现错误时收到通知.我觉得我很天真.
onunload.它看起来有点复杂,所以我先问一下.您可以使用Blob对象从javascript触发文件下载.这是随File API引入的,仍处于Working Draft状态.因此,您将获得有限的浏览器支持.截至2015年,您可以对Blob URL和Blob Constructor提供广泛的浏览器支持.
<div ng-controller="appController" ng-app="app">
<a ng-href="{{ fileUrl }}" download="file.txt">download</a>
</div>
Run Code Online (Sandbox Code Playgroud)
var app = angular.module('app', []);
// Angular prepends "unsafe" tag in ng-href to prevent XSS
// so we need to sanitize this
app.config(['$compileProvider', function ($compileProvider) {
// for Angular 1.0.x and 1.1.x, you should use urlSanitizationWhitelist
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob|ftp):/);
}]);
app.controller('appController', function ($scope, $window) {
// Creating a Blob with our data for download
// this will parse the URL in ng-href such as: blob:http...
var data = 'some data here...',
blob = new Blob([data], { type: 'text/plain' }),
url = $window.URL || $window.webkitURL;
$scope.fileUrl = url.createObjectURL(blob);
});
Run Code Online (Sandbox Code Playgroud)
有一些库可以扩展浏览器对Blob.js的支持
您还应该查看FileSaver.js,它也可以追溯到data:URI.
| 归档时间: |
|
| 查看次数: |
4275 次 |
| 最近记录: |