无法加载PDF文档 - Angular JS - BLOB

Mah*_*lle 5 pdf blob chunked-encoding asp.net-web-api angularjs

我试图从Web API获取PDF文档,并希望在Angular App中显示.获取"无法加载PDF文档错误".我在" 角度应用程序 "帖子中跟随了" AngularJS:显示blob(.pdf) ".然而,我可以通过以下" 使用AngularJS从ASP.NET Web API方法下载文件 "文章成功下载相同的文件.

看起来我得到的文件是"Chunked Transfer Encoded".不知何故,当试图在角度应用程序中显示时,这不会被解码.请指教.

Web API代码:

HttpResponseMessage result = null;
        var localFilePath = @"C:\Test.pdf";

        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.ContentType = new MediaTypeHeaderValue("application/pdf");
            result.Content.Headers.ContentDisposition.FileName = "Test.pdf";
            result.Content.Headers.Add("x-filename", "Test.pdf");
        }

        return result;
Run Code Online (Sandbox Code Playgroud)

角度控制器:

   myModule.controller("pdfviewerController", function ($scope, $http, $log, $sce) {
$http.post('/api/Sample/GetTestFile', {responseType:'arraybuffer'})
 .success(function (response) {      
  var file = new Blob([response], { type: 'application/pdf' });
  var fileURL = URL.createObjectURL(file);
  $scope.content = $sce.trustAsResourceUrl(fileURL);            
 });
});
Run Code Online (Sandbox Code Playgroud)

HTML模板:

<embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>
Run Code Online (Sandbox Code Playgroud)

Mah*_*lle 11

控制器中存在问题. {responseType:'arraybuffer'}是非常需要的.对于$http.get- 它应该是第二个参数.对于$http.post- 它应该是第三个参数.

在上面的例子中,我使用$ http.post,我已经{responseType:'arraybuffer'}作为第二个参数传递.

$http.post('/api/Sample/GetTestFile', {responseType:'arraybuffer'})

更正了代码

$http.post('/api/Sample/GetTestFile','', {responseType:'arraybuffer'})