javascript - 你如何使用 AngularJS 或 Javascript 提供文件下载?

标签 javascript angularjs

我在隐藏的文本区域中有一些文本。单击按钮时,我希望将文本作为 .txt 文件提供下载。这可能使用 AngularJS 或 Javascript 吗?

最佳答案

您可以使用 Blob 执行类似的操作。

<a download="content.txt" ng-href="{{ url }}">download</a>

在你的 Controller 中:

var content = 'file content for example';
var blob = new Blob([ content ], { type : 'text/plain' });
$scope.url = (window.URL || window.webkitURL).createObjectURL( blob );

为了启用 URL:

app = angular.module(...);
app.config(['$compileProvider',
    function ($compileProvider) {
        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/);
}]);

请注意

Each time you call createObjectURL(), a new object URL is created, even if you've already created one for the same object. Each of these must be released by calling URL.revokeObjectURL() when you no longer need them. Browsers will release these automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so.

来源:MDN

关于javascript - 你如何使用 AngularJS 或 Javascript 提供文件下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16514509/

相关文章:

javascript - Lodash uniqWith,怎么说lodash keep last duplicate

javascript - 更改虚拟列phpgrid的位置

javascript - $state.go - 更新 url

angularjs - 我们可以在 angularJS app.js 中一起使用 ngRoute 和 ui.router 吗?

javascript - 使用 ng-repeat 同步数据库中请求的数据

javascript - 单击外部即可关闭滑动面板

javascript - Wordpress 使用 URL 注销并重定向到指定页面

javascript - Angular 表单上传在 Safari 中不起作用,在 Chrome 中起作用

javascript - Angular Material mdTabs - 如何只获得标签动画的效果而不是内容?

javascript - 谁能告诉我植入看起来像这样和类似这样? css和jQuery的效果?