98

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

4

11 回答 11

112

您可以使用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() 来释放它们中的每一个。当文档被卸载时,浏览器会自动释放它们;但是,为了获得最佳性能和内存使用,如果您可以在安全时间显式卸载它们,则应该这样做。

来源:MDN

于 2013-05-13T04:11:06.273 回答
33

只需单击按钮即可使用以下代码进行下载。

在 HTML 中

<a class="btn" ng-click="saveJSON()" ng-href="{{ url }}">Export to JSON</a>

在控制器中

$scope.saveJSON = function () {
			$scope.toJSON = '';
			$scope.toJSON = angular.toJson($scope.data);
			var blob = new Blob([$scope.toJSON], { type:"application/json;charset=utf-8;" });			
			var downloadLink = angular.element('<a></a>');
                        downloadLink.attr('href',window.URL.createObjectURL(blob));
                        downloadLink.attr('download', 'fileName.json');
			downloadLink[0].click();
		};

于 2015-02-16T12:12:46.330 回答
26

尝试这个

<a target="_self" href="mysite.com/uploads/ahlem.pdf" download="foo.pdf">

并访问此站点,它可能对您有所帮助:)

http://docs.angularjs.org/guide/

于 2014-03-08T12:19:32.053 回答
24

这可以在 javascript 中完成,而无需打开另一个浏览器窗口。

window.location.assign('url');

将“url”替换为您的文件的链接。ng-click如果需要从按钮触发下载,可以将其放入函数中并调用它。

于 2014-06-28T09:50:24.740 回答
14

在我们当前的工作项目中,我们有一个不可见的 iFrame,我必须将文件的 url 提供给 iFrame 以获得下载对话框。在按钮单击时,控制器生成动态 url 并触发 $scope 事件,directive我编写的自定义正在列出。如果 iFrame 尚不存在,该指令会将 iFrame 附加到正文并在其上设置 url 属性。

编辑:添加指令

appModule.directive('fileDownload', function ($compile) {
    var fd = {
        restrict: 'A',
        link: function (scope, iElement, iAttrs) {

            scope.$on("downloadFile", function (e, url) {
                var iFrame = iElement.find("iframe");
                if (!(iFrame && iFrame.length > 0)) {
                    iFrame = $("<iframe style='position:fixed;display:none;top:-1px;left:-1px;'/>");
                    iElement.append(iFrame);
                }

                iFrame.attr("src", url);


            });
        }
    };

    return fd;
});

该指令响应一个名为的控制器事件downloadFile

所以在你的控制器中你做

$scope.$broadcast("downloadFile", url);
于 2013-05-13T04:55:58.497 回答
12

您可以设置location.href为包含要让用户下载的数据的数据 URI 。除此之外,我认为仅使用 JavaScript 没有任何方法可以做到这一点。

于 2013-05-13T03:57:15.073 回答
7

只是想补充一点,以防它因为 unsafe:blob:null... 而无法下载文件。当您将鼠标悬停在下载按钮上时,您必须对其进行清理。例如,

var app = angular.module('app', []);

app.config(函数($compileProvider){

$compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/);
于 2014-02-09T23:17:13.243 回答
5

如果您可以在服务器上访问,请考虑按照这个更一般的问题中的回答设置标题。

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"

阅读有关该答案的评论,建议使用比八位字节流更具体的内容类型。

于 2016-08-05T15:45:07.243 回答
4

我遇到了同样的问题并花了很多时间寻找不同的解决方案,现在我加入了这篇文章中的所有评论。我希望它会有所帮助,我的答案在 Internet Explorer 11、Chrome 和 FireFox 上得到了正确测试。

HTML:

<a href="#" class="btn btn-default" file-name="'fileName.extension'"  ng-click="getFile()" file-download="myBlobObject"><i class="fa fa-file-excel-o"></i></a>

指令:

directive('fileDownload',function(){
    return{
        restrict:'A',
        scope:{
            fileDownload:'=',
            fileName:'=',
        },

        link:function(scope,elem,atrs){


            scope.$watch('fileDownload',function(newValue, oldValue){

                if(newValue!=undefined && newValue!=null){
                    console.debug('Downloading a new file'); 
                    var isFirefox = typeof InstallTrigger !== 'undefined';
                    var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
                    var isIE = /*@cc_on!@*/false || !!document.documentMode;
                    var isEdge = !isIE && !!window.StyleMedia;
                    var isChrome = !!window.chrome && !!window.chrome.webstore;
                    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
                    var isBlink = (isChrome || isOpera) && !!window.CSS;

                    if(isFirefox || isIE || isChrome){
                        if(isChrome){
                            console.log('Manage Google Chrome download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var downloadLink = angular.element('<a></a>');//create a new  <a> tag element
                            downloadLink.attr('href',fileURL);
                            downloadLink.attr('download',scope.fileName);
                            downloadLink.attr('target','_self');
                            downloadLink[0].click();//call click function
                            url.revokeObjectURL(fileURL);//revoke the object from URL
                        }
                        if(isIE){
                            console.log('Manage IE download>10');
                            window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName); 
                        }
                        if(isFirefox){
                            console.log('Manage Mozilla Firefox download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var a=elem[0];//recover the <a> tag from directive
                            a.href=fileURL;
                            a.download=scope.fileName;
                            a.target='_self';
                            a.click();//we call click function
                        }


                    }else{
                        alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
                    }
                }
            });

        }
    }
})

在控制器中:

$scope.myBlobObject=undefined;
$scope.getFile=function(){
        console.log('download started, you can show a wating animation');
        serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
        .then(function(data){//is important that the data was returned as Aray Buffer
                console.log('Stream download complete, stop animation!');
                $scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        },function(fail){
                console.log('Download Error, stop animation and show error message');
                                    $scope.myBlobObject=[];
                                });
                            }; 

服务中:

function getStream(params){
                 console.log("RUNNING");
                 var deferred = $q.defer();

                 $http({
                     url:'../downloadURL/',
                     method:"PUT",//you can use also GET or POST
                     data:params,
                     headers:{'Content-type': 'application/json'},
                     responseType : 'arraybuffer',//THIS IS IMPORTANT
                    })
                    .success(function (data) {
                        console.debug("SUCCESS");
                        deferred.resolve(data);
                    }).error(function (data) {
                         console.error("ERROR");
                         deferred.reject(data);
                    });

                 return deferred.promise;
                };

后端(在春天):

@RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
        @RequestBody Map<String,String> spParams
        ) throws IOException {
        OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}
于 2016-05-20T23:40:40.500 回答
3

这在角度上对我有用:

var a = document.createElement("a");
a.href = 'fileURL';
a.download = 'fileName';
a.click();
于 2018-07-05T06:44:41.537 回答
2

我不想要静态网址。我有 AjaxFactory 用于执行所有 ajax 操作。我从工厂获取 url 并将其绑定如下。

<a target="_self" href="{{ file.downloadUrl + '/' + order.OrderId + '/' + fileName }}" download="{{fileName}}">{{fileName}}</a>

谢谢@AhlemMustapha

于 2014-06-16T20:38:28.257 回答