51

嗨,我想知道在使用 angularjs 上传图像之前是否有办法预览图像?我正在使用这个库。https://github.com/danialfarid/angular-file-upload

谢谢。这是我的代码:

模板.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>

控制器.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);
  }); 
}
}
4

4 回答 4

53

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

于 2013-10-01T06:35:52.010 回答
36

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/*">

这对我有用。

于 2015-08-11T22:12:59.740 回答
9

请参阅Bootstrap v3的Jasney 扩展中的图像上传小部件

于 2014-01-20T01:12:19.710 回答
5
  // 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}}" />
于 2017-01-15T10:58:52.907 回答