使用Angularjs在页面中显示文件的预览

时间:2017-02-09 19:11:39

标签: javascript html angularjs

嗨我需要在选择图像或pdf文档时选择文件显示文件的预览:

angular.module('HelloWorldApp', [])
   .controller('HelloWorldController', function($scope, $http, $window, $sce) {
  
  $scope.extensao = '';
  
  $scope.uploadImagem = function (element) {
        var photofile = element.files[0];
        var reader = new FileReader();

        $scope.files = []
        $scope.files.push(element.files[0])

        $scope.extensao = element.files[0].name;
        $scope.type = '';

        reader.onload = function (e) {
            $scope.imagem = e.target.result;
            $scope.$apply();
        };
        reader.readAsDataURL(photofile);
    };
  

    $scope.showImage = function () {

      
        if ($scope.extensao.toLowerCase().includes('.jpg'))
            $scope.type = 'image/jpg';
        if ($scope.extensao.toLowerCase().includes('.png'))
            $scope.type = 'image/png';
        if ($scope.extensao.toLowerCase().includes('.pdf'))
            $scope.type = 'application/pdf';
        if ($scope.extensao.toLowerCase().includes('.doc'))
            $scope.type = 'application/msword';

        var length = $scope.imagem.length;
        var arrayBuffer = new ArrayBuffer(length);
        var uintArray = new Uint8Array(arrayBuffer);
        for (var i = 0; i < length; i++) {
            uintArray[i] = $scope.imagem.charCodeAt(i);
        }

        var file = new Blob([uintArray], { type: $scope.type });
        var fileURL = URL.createObjectURL(file);
        $scope.pdfContent = $sce.trustAsResourceUrl(fileURL);
      
    }


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<div ng-app="HelloWorldApp">
  <div ng-controller="HelloWorldController">
      <label for="fileToUpload">
      <input type="file" style="display:none;" ng-model-instant id="fileToUpload" multiple onchange="angular.element(this).scope().uploadImagem(this)" />
      Select File
      </label>
      <div ng-show="files.length" class="form-group col-xs-10">
        <div ng-repeat="file in files.slice(0)">
          <span class='label label-info'>{{file.webkitRelativePath || file.name}}
          </span>
          <input type="button" value="Open" ng-click="showImage()"/>
        </div>
      </div>
      <div class="corpoConfirma" onloadstart="">
      <object data="{{pdfContent}}" type="{{type}}" style="width:100%; height:100%" />
    </div>
  </div>
</div>

How to read pdf stream in angularjs

此示例未显示预览可能打开新窗口显示,可以帮助我!

1 个答案:

答案 0 :(得分:1)

我使用函数:dataURItoBlob (dataURI)解决了来自stackoverflow的贡献者。并将javascript编辑为更多浏览器。

angular.module('HelloWorldApp', [])
   .controller('HelloWorldController', function($scope, $http, $window, $sce) {
  
  $scope.extensao = '';
  
  $scope.uploadImagem = function (element) {
        var photofile = element.files[0];
        var reader = new FileReader();

        $scope.files = []
        $scope.files.push(element.files[0])

        $scope.extensao = element.files[0].name;
        $scope.type = '';

        reader.onload = function (e) {
            $scope.imagem = e.target.result;
            $scope.$apply();
        };
        reader.readAsDataURL(photofile);
    };
  

function dataURItoBlob(dataURI) {

	// convert base64/URLEncoded data component to raw binary data held in a string
	var byteString;
	if (dataURI.split(',')[0].indexOf('base64') >= 0)
		byteString = atob(dataURI.split(',')[1]);
	else
		byteString = unescape(dataURI.split(',')[1]);

	// separate out the mime component
	var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

	// write the bytes of the string to a typed array
	var ia = new Uint8Array(byteString.length);
	for (var i = 0; i < byteString.length; i++) {
		ia[i] = byteString.charCodeAt(i);
	}

	return new Blob([ia], {type:mimeString});
}

$scope.showImage = function () {

    $scope.extensao = '';
	var imagem = $scope.imagem;

    if (imagem.toLowerCase().indexOf('image/jpeg') > 0) {
        $scope.type = 'image/jpeg';
        $scope.extensao = '.jpg';
    } else
        if (imagem.toLowerCase().indexOf('image/png') > 0) {
            $scope.type = 'image/png';
            $scope.extensao = '.png';
        } else
            if (imagem.toLowerCase().indexOf('application/pdf') > 0) {
                $scope.type = 'application/pdf';
                $scope.extensao = '.pdf';
            } else
                if (imagem.toLowerCase().indexOf('application/msword') > 0) {
                    $scope.type = 'application/msword';
                    $scope.extensao = '.doc';
                } else {
                        $scope.type = 'application/octet-stream';
                        $scope.extensao = '.docx';
                    }

    var decodedImage = dataURItoBlob(imagem);
    var blob = new Blob([decodedImage], { type: $scope.type });
    var fileURL = URL.createObjectURL(blob);
    $scope.pdfContent = $sce.trustAsResourceUrl(fileURL);

}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<div ng-app="HelloWorldApp">
  <div ng-controller="HelloWorldController">
      <label for="fileToUpload">
      <input type="file" style="display:none;" ng-model-instant id="fileToUpload" multiple onchange="angular.element(this).scope().uploadImagem(this)" />
      Select File
      </label>
      <div ng-show="files.length" class="form-group col-xs-10">
        <div ng-repeat="file in files.slice(0)">
          <span class='label label-info'>{{file.webkitRelativePath || file.name}}
          </span>
          <input type="button" value="Open" ng-click="showImage()"/>
        </div>
      </div>
      <div class="corpoConfirma" onloadstart="">
      <object id="teste1" data="{{pdfContent}}" type="{{type}}" style="width:100%; height:100%" />
    </div>
  </div>
</div>