你如何服务于下载与AngularJS或Javascript文件? [英] How do you serve a file for download with AngularJS or Javascript?

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

问题描述

我有一个隐藏textarea的一些文字。当点击一个按钮,我想有下载提供了一个 .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:

in order to enable the URL:

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

请注意,

每个调用createObjectURL(时间),一个新的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天全站免登陆