在上传Angularjs之前预览图像

嗨,我想知道是否有一种方法来预览图像,然后使用angularjs上传它们? 我正在使用这个库。 https://github.com/danialfarid/angular-file-upload

谢谢。 这是我的代码:

template.html

<div ng-controller="picUploadCtr"> <form> <input type="text" ng-model="myModelObj"> <input type="file" ng-file-select="onFileSelect($files)" > <input type="file" ng-file-select="onFileSelect($files)" multiple> </form> </div> 

controller.js

  .controller('picUploadCtr', function($scope, $http,$location, userSettingsService) { $scope.onFileSelect = function($files) { //$files: an array of files selected, each file has name, size, and type. for (var i = 0; i < $files.length; i++) { var $file = $files[i]; $http.uploadFile({ url: 'server/upload/url', //upload.php script, node.js route, or servlet uplaod url) data: {myObj: $scope.myModelObj}, file: $file }).then(function(data, status, headers, config) { // file is uploaded successfully console.log(data); }); } } 

OdeToCode为这个东西提供了很好的服务 。 因此,通过这个简单的指令,您可以轻松预览甚至看到进度条:

 .directive("ngFileSelect",function(){ return { link: function($scope,el){ el.bind("change", function(e){ $scope.file = (e.srcElement || e.target).files[0]; $scope.getFile(); }); } } 

它在所有现代浏览器中工作!

例如: http : //plnkr.co/edit/y5n16v?p=preview

JavaScript的

  $scope.setFile = function(element) { $scope.currentFile = element.files[0]; var reader = new FileReader(); reader.onload = function(event) { $scope.image_source = event.target.result $scope.$apply() } // when the file is read it triggers the onload event above. reader.readAsDataURL(element.files[0]); } 

HTML

 <img ng-src="{{image_source}}"> <input type="file" id="trigger" class="ng-hide" onchange="angular.element(this).scope().setFile(this)" accept="image/*"> 

这对我有效。

从Bootstrap v3的Jasney扩展中查看Image Upload Widget

  // start Picture Preview $scope.imageUpload = function (event) { var files = event.target.files; for (var i = 0; i < files.length; i++) { var file = files[i]; var reader = new FileReader(); reader.onload = $scope.imageIsLoaded; reader.readAsDataURL(file); } } $scope.imageIsLoaded = function (e) { $scope.$apply(function () { $scope.img = e.target.result; }); } <input type='file' ng-model-instant onchange="angular.element(this).scope().imageUpload(event)" /> <img class="thumb" ng-src="{{img}}" />