使用AngularJS从ASP.NET Web API方法下载文件

132
在我的Angular JS项目中,我有一个 锚标签,当被点击时会向WebAPI方法发出HTTP GET请求来获取文件。现在,我希望在请求成功后将文件下载到用户的计算机。我该怎么做?
锚标签:
<a href="#" ng-click="getthefile()">Download img</a>

AngularJS:

$scope.getthefile = function () {        
    $http({
        method: 'GET',
        cache: false,
        url: $scope.appPath + 'CourseRegConfirm/getfile',            
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        }
    }).success(function (data, status) {
        console.log(data); // Displays text data if the file is a text file, binary if it's an image            
        // What should I write here to download the file I receive from the WebAPI method?
    }).error(function (data, status) {
        // ...
    });
}

我的 WebAPI 方法:

[Authorize]
[Route("getfile")]
public HttpResponseMessage GetTestFile()
{
    HttpResponseMessage result = null;
    var localFilePath = HttpContext.Current.Server.MapPath("~/timetable.jpg");

    if (!File.Exists(localFilePath))
    {
        result = Request.CreateResponse(HttpStatusCode.Gone);
    }
    else
    {
        // Serve the file to the client
        result = Request.CreateResponse(HttpStatusCode.OK);
        result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = "SampleImg";                
    }

    return result;
}

1
文件类型是什么?只有图像吗? - Rashmin Javiya
@RashminJaviya 可能是 .jpg、.doc、.xlsx、.docx、.txt 或 .pdf 格式的文件。 - kelsier
你正在使用哪个 .Net 框架? - Rashmin Javiya
@RashminJaviya .net 4.5 - kelsier
文件在WebAPI控制器中不受支持。这仅由MVC控制器支持。 - Kurkula
1
@Kurkula,你应该使用System.IO.File的文件而不是从控制器中获取。 - Javysk
8个回答

245

使用ajax下载二进制文件的支持并不好,仍然处于草案阶段(可以在这里查看)

#简单下载方法:

您可以通过以下代码让浏览器简单地下载所请求的文件,这在所有浏览器中都受支持,并且显然会触发WebApi请求。

$scope.downloadFile = function(downloadPath) { 
    window.open(downloadPath, '_blank', '');  
}

# Ajax二进制下载方法:

在某些浏览器中,可以使用ajax下载二进制文件。以下实现适用于最新版本的Chrome、Internet Explorer、FireFox和Safari。

它使用arraybuffer响应类型,然后将其转换为JavaScript blob,然后将其使用saveBlob方法呈现保存。但是,此方法目前仅适用于Internet Explorer,或将其转换为Blob数据URL,如果MIME类型支持在浏览器中查看,则通过浏览器打开,触发下载对话框。

### Internet Explorer 11支持(已解决) 注意:Internet Explorer 11不喜欢使用已别名的msSaveBlob函数-可能是一种安全功能,但更可能是一个缺陷,因此使用var saveBlob = navigator.msSaveBlob || navigator.webkitSaveBlob...等等来确定可用的saveBlob支持会导致异常;因此,下面的代码现在单独测试navigator.msSaveBlob。感谢微软公司

// Based on an implementation here: web.student.tuwien.ac.at/~e0427417/jsdownload.html
$scope.downloadFile = function(httpPath) {
    // Use an arraybuffer
    $http.get(httpPath, { responseType: 'arraybuffer' })
    .success( function(data, status, headers) {

        var octetStreamMime = 'application/octet-stream';
        var success = false;

        // Get the headers
        headers = headers();

        // Get the filename from the x-filename header or default to "download.bin"
        var filename = headers['x-filename'] || 'download.bin';

        // Determine the content type from the header or default to "application/octet-stream"
        var contentType = headers['content-type'] || octetStreamMime;

        try
        {
            // Try using msSaveBlob if supported
            console.log("Trying saveBlob method ...");
            var blob = new Blob([data], { type: contentType });
            if(navigator.msSaveBlob)
                navigator.msSaveBlob(blob, filename);
            else {
                // Try using other saveBlob implementations, if available
                var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
                if(saveBlob === undefined) throw "Not supported";
                saveBlob(blob, filename);
            }
            console.log("saveBlob succeeded");
            success = true;
        } catch(ex)
        {
            console.log("saveBlob method failed with the following exception:");
            console.log(ex);
        }

        if(!success)
        {
            // Get the blob url creator
            var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
            if(urlCreator)
            {
                // Try to use a download link
                var link = document.createElement('a');
                if('download' in link)
                {
                    // Try to simulate a click
                    try
                    {
                        // Prepare a blob URL
                        console.log("Trying download link method with simulated click ...");
                        var blob = new Blob([data], { type: contentType });
                        var url = urlCreator.createObjectURL(blob);
                        link.setAttribute('href', url);

                        // Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
                        link.setAttribute("download", filename);

                        // Simulate clicking the download link
                        var event = document.createEvent('MouseEvents');
                        event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                        link.dispatchEvent(event);
                        console.log("Download link method with simulated click succeeded");
                        success = true;

                    } catch(ex) {
                        console.log("Download link method with simulated click failed with the following exception:");
                        console.log(ex);
                    }
                }

                if(!success)
                {
                    // Fallback to window.location method
                    try
                    {
                        // Prepare a blob URL
                        // Use application/octet-stream when using window.location to force download
                        console.log("Trying download link method with window.location ...");
                        var blob = new Blob([data], { type: octetStreamMime });
                        var url = urlCreator.createObjectURL(blob);
                        window.location = url;
                        console.log("Download link method with window.location succeeded");
                        success = true;
                    } catch(ex) {
                        console.log("Download link method with window.location failed with the following exception:");
                        console.log(ex);
                    }
                }

            }
        }

        if(!success)
        {
            // Fallback to window.open method
            console.log("No methods worked for saving the arraybuffer, using last resort window.open");
            window.open(httpPath, '_blank', '');
        }
    })
    .error(function(data, status) {
        console.log("Request failed with status: " + status);

        // Optionally write the error out to scope
        $scope.errorDetails = "Request failed with status: " + status;
    });
};

##用法:

var downloadPath = "/files/instructions.pdf";
$scope.downloadFile(downloadPath);

###注意事项:

您需要修改您的WebApi方法,以返回以下标头:

  • 我使用了x-filename标头来发送文件名。这是一个自定义标头,方便起见,但您也可以使用正则表达式从content-disposition标头中提取文件名。

  • 您还应该为响应设置content-type MIME标头,以便浏览器知道数据格式。

希望对您有所帮助。


你能在 window.open 中发送参数吗?比如一个 ID 数组? - AlexandruC
1
抱歉,我没看到那个。顺便说一下,这个功能运行得非常好。甚至比filesaver.js更好。 - Jeeva J
1
当我尝试通过这种方法下载微软可执行文件时,返回的 blob 大小大约是实际文件大小的 1.5 倍。下载的文件具有错误的 blob 大小。您认为这可能是为什么?根据查看 fiddler 的结果,响应的大小是正确的,但将内容转换为 blob 会以某种方式增加它。 - user3517454
1
终于找到问题所在了...我已经将服务器代码从post更改为get,但我没有改变$http.get的参数。因此,响应类型从未被设置为arraybuffer,因为它作为第三个参数传递而不是第二个参数。 - user3517454
1
@RobertGoldwein 你可以这样做,但是假设如果你正在使用一个angularjs应用程序,你希望用户保持在应用程序中,下载开始后状态和使用功能的能力得以维持。如果直接导航到下载页面,则无法保证应用程序仍然处于活动状态,因为浏览器可能无法按照我们的期望处理下载。想象一下,如果服务器返回500或404错误,用户现在已经退出了Angular应用程序。最简单的建议是使用window.open在新窗口中打开链接。 - Scott
显示剩余27条评论

10

C# WebApi 与 Angular JS 认证一起使用时可下载 PDF

Web Api 控制器

[HttpGet]
    [Authorize]
    [Route("OpenFile/{QRFileId}")]
    public HttpResponseMessage OpenFile(int QRFileId)
    {
        QRFileRepository _repo = new QRFileRepository();
        var QRFile = _repo.GetQRFileById(QRFileId);
        if (QRFile == null)
            return new HttpResponseMessage(HttpStatusCode.BadRequest);
        string path = ConfigurationManager.AppSettings["QRFolder"] + + QRFile.QRId + @"\" + QRFile.FileName;
        if (!File.Exists(path))
            return new HttpResponseMessage(HttpStatusCode.BadRequest);

        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        //response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
        Byte[] bytes = File.ReadAllBytes(path);
        //String file = Convert.ToBase64String(bytes);
        response.Content = new ByteArrayContent(bytes);
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
        response.Content.Headers.ContentDisposition.FileName = QRFile.FileName;

        return response;
    }

AngularJS服务

this.getPDF = function (apiUrl) {
            var headers = {};
            headers.Authorization = 'Bearer ' + sessionStorage.tokenKey;
            var deferred = $q.defer();
            $http.get(
                hostApiUrl + apiUrl,
                {
                    responseType: 'arraybuffer',
                    headers: headers
                })
            .success(function (result, status, headers) {
                deferred.resolve(result);;
            })
             .error(function (data, status) {
                 console.log("Request failed with status: " + status);
             });
            return deferred.promise;
        }

        this.getPDF2 = function (apiUrl) {
            var promise = $http({
                method: 'GET',
                url: hostApiUrl + apiUrl,
                headers: { 'Authorization': 'Bearer ' + sessionStorage.tokenKey },
                responseType: 'arraybuffer'
            });
            promise.success(function (data) {
                return data;
            }).error(function (data, status) {
                console.log("Request failed with status: " + status);
            });
            return promise;
        }

都可以

Angular JS控制器调用服务

vm.open3 = function () {
        var downloadedData = crudService.getPDF('ClientQRDetails/openfile/29');
        downloadedData.then(function (result) {
            var file = new Blob([result], { type: 'application/pdf;base64' });
            var fileURL = window.URL.createObjectURL(file);
            var seconds = new Date().getTime() / 1000;
            var fileName = "cert" + parseInt(seconds) + ".pdf";
            var a = document.createElement("a");
            document.body.appendChild(a);
            a.style = "display: none";
            a.href = fileURL;
            a.download = fileName;
            a.click();
        });
    };

最后是HTML网页

<a class="btn btn-primary" ng-click="vm.open3()">FILE Http with crud service (3 getPDF)</a>

这将进行重构,现在只分享代码,希望它能帮助到某人,因为我花了一段时间才让它正常工作。


以上代码在所有系统上都可以运行,除了ios系统。如果你需要在ios上运行,请按照以下步骤操作:步骤1:检查是否为ios系统。https://dev59.com/EGox5IYBdhLWcg3wr2To步骤2:(如果是ios系统)使用此链接。https://dev59.com/DmAf5IYBdhLWcg3wlDmb - tfa
注意:https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL#Memory_management - anatol

6
对我来说,Web API 是使用 Rails 和客户端 Angular 进行开发的,同时还应用了 RestangularFileSaver.jsWeb API(网络应用程序编程接口)
module Api
  module V1
    class DownloadsController < BaseController

      def show
        @download = Download.find(params[:id])
        send_data @download.blob_data
      end
    end
  end
end

HTML

 <a ng-click="download('foo')">download presentation</a>

Angular 控制器

 $scope.download = function(type) {
    return Download.get(type);
  };

Angular 服务

'use strict';

app.service('Download', function Download(Restangular) {

  this.get = function(id) {
    return Restangular.one('api/v1/downloads', id).withHttpConfig({responseType: 'arraybuffer'}).get().then(function(data){
      console.log(data)
      var blob = new Blob([data], {
        type: "application/pdf"
      });
      //saveAs provided by FileSaver.js
      saveAs(blob, id + '.pdf');
    })
  }
});

你是如何使用Filesaver.js的?你是如何实现它的? - Alan Dunning

2

我们还需要开发一种解决方案,即使是需要身份验证的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);
            });
        };
    }] 
});

步骤2:创建模板
<a href="" class="btn btn-primary" ng-click="downloadPdf()">Download</a>

步骤三:使用它。
<pdf-download url="/some/path/to/a.pdf" filename="my-awesome-pdf"></pdf-download>

这将呈现一个蓝色按钮。当点击后,将下载一个PDF文件(注意:后台必须以Base64编码传递PDF!)并放置在href中。按钮变为绿色并将文本切换为保存。用户可以再次点击,并将出现标准的下载文件对话框,用于文件my-awesome.pdf


1
将您的文件作为base64字符串发送。
 var element = angular.element('<a/>');
                         element.attr({
                             href: 'data:attachment/csv;charset=utf-8,' + encodeURI(atob(response.payload)),
                             target: '_blank',
                             download: fname
                         })[0].click();

如果attr方法在Firefox中无法工作,您也可以使用JavaScript的setAttribute方法。

var blob = new Blob([atob(response.payload)], { "data":"attachment/csv;charset=utf-8;" }); saveAs(blob, 'filename'); - PPB
谢谢PPB,你的解决方案对我很有帮助,除了atob。这对我来说不是必需的。 - Larry Flewwelling

0
你可以实现一个showfile函数,该函数接受从WEBApi返回的数据和要下载的文件名作为参数。我创建了一个单独的浏览器服务来识别用户的浏览器,并根据浏览器处理文件的渲染。例如,如果目标浏览器是iPad上的Chrome,则必须使用JavaScript的FileReader对象。
FileService.showFile = function (data, fileName) {
    var blob = new Blob([data], { type: 'application/pdf' });

    if (BrowserService.isIE()) {
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    }
    else if (BrowserService.isChromeIos()) {
        loadFileBlobFileReader(window, blob, fileName);
    }
    else if (BrowserService.isIOS() || BrowserService.isAndroid()) {
        var url = URL.createObjectURL(blob);
        window.location.href = url;
        window.document.title = fileName;
    } else {
        var url = URL.createObjectURL(blob);
        loadReportBrowser(url, window,fileName);
    }
}


function loadFileBrowser(url, window, fileName) {
    var iframe = window.document.createElement('iframe');
    iframe.src = url
    iframe.width = '100%';
    iframe.height = '100%';
    iframe.style.border = 'none';
    window.document.title = fileName;
    window.document.body.appendChild(iframe)
    window.document.body.style.margin = 0;
}

function loadFileBlobFileReader(window, blob,fileName) {
    var reader = new FileReader();
    reader.onload = function (e) {
        var bdata = btoa(reader.result);
        var datauri = 'data:application/pdf;base64,' + bdata;
        window.location.href = datauri;
        window.document.title = fileName;
    }
    reader.readAsBinaryString(blob);
}

1
感谢Scott发现这些问题。我已经进行了重构并添加了解释。 - Erkin Djindjiev

0

我已经浏览了各种解决方案,发现以下方法对我非常有效。

在我的情况下,我需要发送带有某些凭据的POST请求。 将jQuery添加到脚本中会增加一些额外开销。 但是这样做是值得的。

var printPDF = function () {
        //prevent double sending
        var sendz = {};
        sendz.action = "Print";
        sendz.url = "api/Print";
        jQuery('<form action="' + sendz.url + '" method="POST">' +
            '<input type="hidden" name="action" value="Print" />'+
            '<input type="hidden" name="userID" value="'+$scope.user.userID+'" />'+
            '<input type="hidden" name="ApiKey" value="' + $scope.user.ApiKey+'" />'+
            '</form>').appendTo('body').submit().remove();

    }

-1
在你的组件即AngularJS代码中:
function getthefile (){
window.location.href='http://localhost:1036/CourseRegConfirm/getfile';
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接