gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:43:36 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com