gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:50:38 25 4
gpt4 key购买 nike

我正在尝试从 Web API 获取 PDF 文档,并希望在 Angular 应用程序中显示。收到“无法加载 PDF 文档错误”。我已关注“AngularJS: Display blob (.pdf) in an angular app”帖子。然而,我可以通过关注“Download file from an ASP.NET Web API method using AngularJS”帖子成功下载相同的文件。

看起来我得到的文件是“分块传输编码”。不知何故,当尝试在 Angular 应用程序中显示时,这没有被解码。请指教。

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;

Angular Controller :

   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>

最佳答案

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

在上面的情况下,我使用 $http.post 并且已传递 {responseType:'arraybuffer'} 作为第二个参数。

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

更正代码

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

关于angularjs - 无法加载 PDF 文档 - Angular JS - BLOB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28093736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com