Angularjs简单文件下载导致路由器重定向

Upv*_*ote 78 angularjs

HTML:

<a href="mysite.com/uploads/asd4a4d5a.pdf" download="foo.pdf">
Run Code Online (Sandbox Code Playgroud)

上传获得唯一的文件名,而真实姓名保存在数据库中.我想实现一个简单的文件下载.但上面的代码重定向到/因为:

$routeProvider.otherwise({
    redirectTo: '/', 
    controller: MainController
});
Run Code Online (Sandbox Code Playgroud)

我试过了

$scope.download = function(resource){
    window.open(resource);
}
Run Code Online (Sandbox Code Playgroud)

但这只是在新窗口中打开文件.

任何想法如何为任何文件类型启用真正的下载?

jes*_*vin 114

https://docs.angularjs.org/guide/$location#html-link-rewriting

在如下情况下,链接不会被重写; 相反,浏览器将执行整页重新加载到原始链接.

  • 包含目标元素的链接示例:
    <a href="/ext/link?a=b" target="_self">link</a>

  • 转到其他域的绝对链接示例:
    <a href="http://angularjs.org/">link</a>

  • 以'/'开头的链接,在定义base时导致不同的基本路径示例:
    <a href="/not-my-base/link">link</a>

所以在你的情况下,你应该像这样添加一个目标属性......

<a target="_self" href="example.com/uploads/asd4a4d5a.pdf" download="foo.pdf">
Run Code Online (Sandbox Code Playgroud)

  • 好点@JanŚwięcki,我更新了我的答案. (2认同)

aix*_*aix 32

我们还必须开发一种解决方案,甚至可以使用需要身份验证的API(参见本文)

简而言之,使用AngularJS是我们如何做到的:

第1步:创建专用指令

// jQuery needed, uses Bootstrap classes, adjust the path of templateUrl
app.directive('pdfDownload', function() {
return {
    restrict: 'E',
    templateUrl: '/path/to/pdfDownload.tpl.html',
    scope: true,
    link: function(scope, element, attr) {
        var anchor = element.children()[0];

        // When the download starts, disable the link
        scope.$on('download-start', function() {
            $(anchor).attr('disabled', 'disabled');
        });

        // When the download finishes, attach the data to the link. Enable the link and change its appearance.
        scope.$on('downloaded', function(event, data) {
            $(anchor).attr({
                href: 'data:application/pdf;base64,' + data,
                download: attr.filename
            })
                .removeAttr('disabled')
                .text('Save')
                .removeClass('btn-primary')
                .addClass('btn-success');

            // Also overwrite the download pdf function to do nothing.
            scope.downloadPdf = function() {
            };
        });
    },
    controller: ['$scope', '$attrs', '$http', function($scope, $attrs, $http) {
        $scope.downloadPdf = function() {
            $scope.$emit('download-start');
            $http.get($attrs.url).then(function(response) {
                $scope.$emit('downloaded', response.data);
            });
        };
    }] 
});
Run Code Online (Sandbox Code Playgroud)

第2步:创建模板

<a href="" class="btn btn-primary" ng-click="downloadPdf()">Download</a>
Run Code Online (Sandbox Code Playgroud)

第3步:使用它

<pdf-download url="/some/path/to/a.pdf" filename="my-awesome-pdf"></pdf-download>
Run Code Online (Sandbox Code Playgroud)

这将呈现一个蓝色按钮.单击时,将下载PDF(注意:后端必须以Base64编码提供PDF!)并放入href.该按钮变为绿色并将文本切换为" 保存".用户可以再次单击,将显示文件my-awesome.pdf的标准下载文件对话框.

我们的示例使用PDF文件,但显然您可以提供任何二进制格式,只要它已正确编码.

  • 大文件怎么样?1GB?10GB? (4认同)
  • 很好的解决方案,但有两个限制:1.用户必须单击按钮两次,2.IE 11不支持下载属性,因此您无法设置文件名. (2认同)

hav*_*ino 8

如果您需要更高级的指令,我建议我在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>
Run Code Online (Sandbox Code Playgroud)

指令:

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');
                    }
                }
            });

        }
    }
})
Run Code Online (Sandbox Code Playgroud)

控制器:

$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=[];
                                });
                            }; 
Run Code Online (Sandbox Code Playgroud)

在服务中:

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;
                };
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)