我在隐藏的文本区域中有一些文本。单击按钮时,我希望将文本作为 .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/