加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:58:49 所属栏目:安全 来源:网络整理
导读:我试图从Web API获取PDF文档,并希望在Angular App中显示.获
我试图从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’})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读