我在隐藏的文本区域中有一些文本。单击一个按钮后,我希望提供文本作为.txt文件下载。使用AngularJS或Javascript可以做到吗?
我在隐藏的文本区域中有一些文本。单击一个按钮后,我希望提供文本作为.txt文件下载。使用AngularJS或Javascript可以做到吗?
Answers:
您可以使用进行类似的操作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
$scope.url对我没有用。我不得不使用window.location。
                    download尽管caniuse.com/#feat=download
                    只需单击按钮即可使用以下代码下载。
在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();
		};$http.get(...)请务必将responseType:'arraybuffer'喜欢这里解释:stackoverflow.com/questions/21628378/...
                    试试这个
<a target="_self" href="mysite.com/uploads/ahlem.pdf" download="foo.pdf">并访问此网站可能对您有帮助:)
download任何IE或Safari版本仍不支持的属性。在此处查看:caniuse.com/#feat=download
                    在我们当前的工作项目中,我们有一个不可见的iFrame,我必须将文件的网址提供给iFrame以获取下载对话框。单击按钮后,控制器将生成动态URL,并触发一个$ scope事件,其中directive列出了我编写的自定义项。如果该指令尚不存在,则该指令会将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);您可以设置location.href一个数据URI,其中包含要让用户下载的数据。除此之外,我认为仅凭JavaScript无法实现任何方法。
$location.href更改为$window.location.href
                    只是要添加一下,以防由于unsafe:blob:null ...而无法下载文件时,将鼠标悬停在下载按钮上时,必须对其进行清理。例如,
var app = angular.module('app',[]);
app.config(function($ compileProvider){
$compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/);
如果您可以在服务器上访问,请考虑按照此更常见的问题中的回答设置标题。
Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"阅读有关该答案的评论时,建议使用比八位字节流更具体的Content-Type。
我遇到了同样的问题,花了很多时间找到不同的解决方案,现在我加入本文中的所有评论,希望对我有所帮助,我的答案已在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;
                };BACKEND(在SPRING上):
@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;
}这在角度上对我有用:
var a = document.createElement("a");
a.href = 'fileURL';
a.download = 'fileName';
a.click();data:text/plain;base64,${btoa(theStringGoesHere)}