Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

angularjs - Failed to load PDF document - Angular JS - BLOB

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.

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

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 Template:

<embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

In above case, i am using $http.post and i have passed {responseType:'arraybuffer'} as second parameter.

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

Corrected code

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...