无法加载 PDF 文档 - Angular JS - BLOB [英] Failed to load PDF document - Angular JS - BLOB
问题描述
我正在尝试从 Web API 获取 PDF 文档,并希望在 Angular App 中显示.出现无法加载 PDF 文档错误".我已关注"AngularJS:在 Angular 应用中显示 blob (.pdf)"的帖子.而我可以按照使用 AngularJS 从 ASP.NET Web API 方法下载文件" 帖子.
I am trying to get PDF document from Web API, and want to show in Angular App. Getting "Failed to load PDF document error". I have followed "AngularJS: Display blob (.pdf) in an angular app" post. Whereas, i can download the same file successfully by following "Download file from an ASP.NET Web API method using AngularJS" post.
看起来我得到的文件是分块传输编码".不知何故,当尝试在 angular 应用程序中显示时,这并没有被解码.请指教.
Looks like i am getting the file as "Chunked Transfer Encoded". Somehow this is not getting decoded when trying to show in angular app. Please advise.
Web API 代码:
Web API Code:
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
- 它应该是第三个参数.
problem is there in controller.
{responseType:'arraybuffer'}
is verymuch required.
For $http.get
- It should be second parameter.
For $http.post
- It should be third parameter.
在上面的例子中,我使用了 $http.post 并且我传递了 {responseType:'arraybuffer'}
作为第二个参数.
In above case, i am using $http.post and i have passed {responseType:'arraybuffer'}
as second parameter.
$http.post('/api/Sample/GetTestFile', {responseType:'arraybuffer'})
更正的代码
$http.post('/api/Sample/GetTestFile','', {responseType:'arraybuffer'})
这篇关于无法加载 PDF 文档 - Angular JS - BLOB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!