angularjs – 无法加载PDF文档 – Angular JS – BLOB

前端之家收集整理的这篇文章主要介绍了angularjs – 无法加载PDF文档 – Angular JS – BLOB前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图从Web API获取PDF文档,并希望在Angular App中显示.获取“无法加载PDF文档错误”.
我跟着
AngularJS: Display blob (.pdf) in an angular app”发布.
然而,我可以通过关注“ Download file from an ASP.NET Web API method using AngularJS”帖子成功下载相同的文件.

看起来我得到的文件是“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;

角度控制器:

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

HTML模板:

<embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>
控制器中存在问题.
{responseType:’arraybuffer’}非常需要.
对于$http.get – 它应该是第二个参数.
对于$http.post – 它应该是第三个参数.

在上面的例子中,我使用$http.post并且我已经通过{responseType:’arraybuffer’}作为第二个参数.

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

更正了代码

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

原文链接:https://www.f2er.com/angularjs/143735.html

猜你在找的Angularjs相关文章