0

I am grabbing a PDF file from an input html and trying to make it display using the HTML5 File API, i am able to console.log the file url but its not displaying in my iframe:

Here is my html:

<html ng-app="PDFReaderApp">
<head>
<title> Automatically get your GPA from submitting in your transcript pdf file </title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<script src="./pdf.js" ></script>
<script src="./app.js" ></script>
<script src="./controllers.js"></script>

<style>
iframe {
  height: 500px;
  width: 400px;
  margin: 2em;
}
</style>
</head>
<body ng-controller="TranscriptReaderCtrl">

 <input id="inputPDF" type="file" accept="application/pdf" onchange="angular.element(this).scope().getPDF(this.files)" />
 <div id="display">
  <iframe id="viewer" ng-src="{{fileUrl}}" ></iframe>
 </div>
</body>
</html>

and my angularjs controller code:

function TranscriptReaderCtrl($http, $scope, $window, $sce) {
 $scope.uploadedPDF = "";
 $scope.fileUrl = "";

 $scope.getPDF = function(files) {
    var fileUrl = $window.URL.createObjectURL(files[0]);
    console.log(fileUrl);
    $scope.fileUrl = $sce.trustAsResourceUrl(fileUrl);
    console.log($scope.fileUrl);
 }
}
mding5692
  • 806
  • 1
  • 10
  • 34
  • do run digest cycle once your events get complete, [read this answer](http://stackoverflow.com/a/41250430/2435473) for more information – Pankaj Parkar Dec 21 '16 at 05:51
  • Thanks, I've tried it but now I just have a iframe displaying a blank file: Resource interpreted as Document but transferred with MIME type application/pdf: "blob:null/5e8fac22-159b-4338-935f-ff32b9ff5cb4" <== is this the issue? – mding5692 Dec 21 '16 at 05:56

1 Answers1

1

The onchange event of the input file is not an angular event, you can see that easily with the work you have to do get your scope in the event handler.

So angular will not be aware of the change made to the model during this event.

To force it to refresh the view and so impact model changes you will have to run a digest cycle by calling $scope.$apply() at the end of the getPDF function.

Regarding the loading error, you will certainly have to add blob:// to the angular url whitelist:

var app = angular.module( 'myApp', [] )
.config( [
    '$compileProvider',
    function( $compileProvider )
    {   
        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob):/);
        // Angular before v1.2 uses     $compileProvider.urlSanitizationWhitelist(...)
    }
]);
Piou
  • 1,056
  • 1
  • 7
  • 10