从服务器下载文件并在angularjs中提供文件名 [英] Download a file from server and giving filename in angularjs

查看:142
本文介绍了从服务器下载文件并在angularjs中提供文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的服务器(spring mvc控制器)下载一个zip文件。
这里是我在angularjs(1.5)控制器中下载zip文件的代码。

I am trying to download a zip file from my server (spring mvc controller). here is my code in angularjs (1.5) controller to download zip file.

   $http({
            url: '/myurl',
            method: 'GET',
            headers: {
                'Content-type': 'application/zip'
            },
            responseType: 'arraybuffer'
        }).success(function (data,status,headers) {
            var blob = new Blob([data], {type: "application/zip"});
            var objectUrl = URL.createObjectURL(blob);                
            var file = headers('Content-Disposition');               

            window.open(objectUrl);

        });

以上代码有效,但我需要提供我在响应标题中获取的文件名。我从头文件('Content-Disposition')获取文件名如何使用此文件名下载文件?目前它提供任何随机文件名。

Above code works, but I need to give file name which I am getting in the response header. I got the file name from header('Content-Disposition') how to use this file name to downloaded file ? currently it is giving any random file name.

我尝试下面的代码它在chrome中工作,但它不能在mozilla中运行...是否有任何其他解决方案适用于所有浏览器?

I tried below code it works in chrome but its not working in mozilla... is there any other solution which works in all browsers ?

            //var anchor = document.createElement("a");
            //anchor.download = "ATMOSLogFiles.zip";
            //anchor.href = objectUrl;
            //anchor.click();

感谢您的帮助!

推荐答案

基于blob的解决方案:



您可以使用 angular-file-saver 来实现这一目标。

An blob based solution:

You could use angular-file-saver to achieve this.

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

app.controller('ExampleCtrl', ['FileSaver', 'Blob', function () {
    $scope.download = function () {
        var myData = new Blob([text], { type: 'text/plain;charset=utf-8' });
        FileSaver.saveAs(myData, 'text.txt');
    }
}]);






基于HTML5的其他解决方案:



使用HTML5的一种简单方法下载属性 / MDN文档。不需要blob。任何浏览器都支持此属性。浏览器版本支持AngularJS(不包括IE10 / IE11 - IE Edge支持它)。


An other solution based on HTML5:

A simple way by using the HTML5 download attribute / MDN documentation. No need for blobs. This attribute is supported by any browser & browser version which supports AngularJS (excluding IE10/IE11 - IE Edge does support it).

<a href="<downloadLink>" download="fileName">Download</a>

这篇关于从服务器下载文件并在angularjs中提供文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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