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>
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'})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With