您如何使用 AngularJS 或 Javascript 提供文件以供下载? [英] How do you serve a file for download with AngularJS or Javascript?

查看:22
本文介绍了您如何使用 AngularJS 或 Javascript 提供文件以供下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some text in a hidden textarea. When a button is clicked I would like to have the text offered for download as a .txt file. Is this possible using AngularJS or Javascript?

推荐答案

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

You can do something like this using Blob.

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

在您的控制器中:

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):/);
}]);

请注意

每次调用 createObjectURL() 时,都会创建一个新的对象 URL,即使您已经为同一个对象创建了一个 URL.当您不再需要它们时,必须通过调用 URL.revokeObjectURL() 来释放它们中的每一个.当文档被卸载时,浏览器会自动释放这些;但是,为了获得最佳性能和内存使用,如果有可以明确卸载它们的安全时间,则应该这样做.

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

这篇关于您如何使用 AngularJS 或 Javascript 提供文件以供下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆