Upload pictures, preview pictures

General idea:

I wrote a fileModel instruction, which is triggered when a file is selected, and the controller method is called in the instruction for graphic echo processing.

Fake code:

jsp:

<div class="form-group">

<label class="col-md-4 control-label">System icon</label>

<div class="col-md-4">

<input type="file" file-model="myFile"/>

<img data-ng-src="{{updateSysinfo.sysIcon}}" />

</div>

</div>

js: directive:

.directive('fileModel', ['$parse', function ($parse) {

                return {

                    restrict: 'A',

                    link: function(scope, element, attrs, ngModel) {

                        var model = $parse(attrs.fileModel);

                        var modelSetter = model.assign;

                        element.bind('change', function(event){

                            scope.$apply(function(){

                                modelSetter(scope, element[0].files[0]);

                            });

                            //Attachment preview

                            scope.file = (event.srcElement || event.target).files[0];

                            scope.getFile(element[0].files);//Note: getFile() is a method in the controller, which is called by an instruction.

                        });

                    }

                };

       }]);

Controller:

var SysInfoController = ["$scope",'$state','Messages','$modal','UrlManager', //

'SysInfoService','HttpService', 'PlatformService',//

function($scope,$state,messages,$modal,urlManager,//

sysInfoService,httpService, platformService) {

      //Call the $scope.getFile method through the instruction

     $scope.getFile = function (files) {

        $scope.reader = new FileReader(); 

            $scope.reader.readAsDataURL(files[0]); //FileReader method, convert the image to base64

            $scope.reader.onload = function(ev) {

            $scope.$apply(function(){

            $scope.updateSysinfo.sysIcon=ev.target.result //接收base64

            })

            };

        };

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326959056&siteId=291194637