Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ AngularJS achieve picture upload feature     - Java Foundation - Getting Start (Programming)

- Oracle first Automated Installation Packages (Database)

- Zabbix API and PHP configuration (Server)

- Present Situation and Development Trend of firewall products (Linux)

- WebLogic 12c Configuration Node Manager Managed Server (Database)

- Compile and install LNMP under CentOS 6.5 (Server)

- Java Concurrency -volatile keywords (Programming)

- Nginx is used to build the cache module srcache_nginx (Server)

- Use nice, cpulimit and cgroups limit cpu usage (Linux)

- See how --nand flash timing diagram of a read operation Comments (Programming)

- Cacti installation deployment under CentOS 6.6 (Server)

- How to install Hadoop on CentOS7 (Server)

- PostgreSQL Source Customization: Online global read only (Database)

- Linux, rename the file or folder (mv command and rename command) (Linux)

- Using the Linux VNC service (Server)

- Oracle 11g partition maintenance (two) - Coalescing Partitions (Database)

- NGINX Plus now fully supports HTTP / 2 (Server)

- Linux cron job (Linux)

- Linux novice common commands (Linux)

- Kibana Apache Password Authentication (Server)

 
         
  AngularJS achieve picture upload feature
     
  Add Date : 2017-08-31      
         
       
         
  First, foreword

When the previous period of time to do the project, a problem is encountered AngularJS achieve image preview and upload function, then consult the documentation (documents are in English) toss a long time before it comes out, the whole process will now be sorted out, a friend in need can refer look, if you have a better way, welcome message exchange ~~ word does not say directly see realize.

Second, the specific realization

1, html tag structure

< Input type = "file" file-model = "myFile" />
< Div class = "col-md-12">
    < Img ng-src = "{{imageSrc}}" style = "max-width: 300px; max-height: 300px; margin: 0 auto; display: block;" />
< / Div>

input file upload tags, div wrapped img tags for image preview area

2. Define directive

        angular.module ( 'app')
            .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 ();
                        });
                    }
                };
            }]);

input tag attributes file-model That is Angular instructions in the link method code above, we bind a command element file-model where a change event, change the method to get the file object you want to upload, and call controller in getFile () method (see controller)

3, the definition of controller UploaderControler

        angular.module ( 'app')
            .controller ( 'UploaderController', function ($ scope, fileReader) {
                $ Scope.getFile = function () {
                    fileReader.readAsDataUrl ($ scope.file, $ scope)
                                  .then (function (result) {
                                      $ Scope.imageSrc = result;
                                  });
                };
            })

The controller defines a UploaderController, the controller is defined in its scope getFile () method, getFile method called fileReader service in readAsDataUrl method that generated the image address url, and returns the result getFile , it returns the url assigned to $ scope.imageSrc, according to a two-way data binding mechanism Angular, img element ng-src url attribute value, then you can preview the image on the page. How fileReader service define it?

4, the definition of service fileReader

      angular.module ( 'app')
            .factory ( 'fileReader', [ "$ q", "$ log", function ($ q, $ log) {
                var onLoad = function (reader, deferred, scope) {
                    return function () {
                        scope. $ apply (function () {
                            deferred.resolve (reader.result);
                        });
                    };
                };
        
                var onError = function (reader, deferred, scope) {
                    return function () {
                        scope. $ apply (function () {
                            deferred.reject (reader.result);
                        });
                    };
                };
        
                var getReader = function (deferred, scope) {
                    var reader = new FileReader ();
                    reader.onload = onLoad (reader, deferred, scope);
                    reader.onerror = onError (reader, deferred, scope);
                    return reader;
                };
        
                var readAsDataURL = function (file, scope) {
                    var deferred = $ q.defer ();
                    var reader = getReader (deferred, scope);
                    reader.readAsDataURL (file);
                    return deferred.promise;
                };
        
                return {
                    readAsDataUrl: readAsDataURL
                };
            }])

fileReader service acquired mainly to generate complete file url address to return to the preview view.

5, Annex uploaded to achieve

Upload attachment mainly to the interface page form data through the background provided written to the database, add the following code in the implementation of the controller UploaderControler:

              // Populate the form data
                var postData = {
                    vacationType: $ scope.leave.type,
                    reason: $ scope.leave.reason,
                    familyRelation: + $ scope.leave.type == 7 $ scope.leave.relation:? "",
                    startTime: startTime,
                    endTime: endTime,
                    fileName: $ scope.imageSrc,
                    workDelivers: workDelivers,
                    ccmailNickNames: sendPersons,
                    realDays: + $ scope.leave.type == 8 $ scope.leave.timeLong:? ""
                };

                var promise = postMultipart ( '/ maldives / leave / save', postData);

                function postMultipart (url, data) {
                    var fd = new FormData ();
                    angular.forEach (data, function (val, key) {
                        fd.append (key, val);
                    });
                    var args = {
                        method: 'POST',
                        url: url,
                        data: fd,
                        headers: { 'Content-Type': undefined},
                        transformRequest: angular.identity
                    };
                    return $ http (args);
                }

postData data in a form (including uploading a picture message), '/ maldives / leave / save' represents the requested background data interface, $ http Angular is built service, can send a GET or POST request to the background.

Third, Angular the service, controller, directive awareness and understanding

Service is a singleton object in AngluarJS an alias. These singleton objects are often passed around, to ensure that every time you access to all the same instance. Based on this idea, singleton object so that we can achieve some pretty cool feature, which lets a lot of controller and the value of its internal access directive.

controller to service, dependencies, and other objects in series together, and then put them through a scope associated with the view. If in your view there need to deal with complex business logic, then put them inside the controller is also a very good choice.

Angular directive is the definition of a code snippet, you can use it to manipulate the DOM, you can also use it for user interaction.
     
         
       
         
  More:      
 
- RHEL6 install Python and other packages from source (Linux)
- Linux AS4 VPN server in conjunction with a firewall perfect (Linux)
- Linux landing problem (Linux)
- Linux Samba server-side structures and the use of the client (Server)
- GitLab Guide installation under Ubuntu 14.04 (Server)
- SQLite database commonly used sentences and visualization tools on MAC MeasSQLlite use (Database)
- Java class HashSet (Programming)
- Installed in the desktop version of Ubuntu Unity Tweak Tool (Linux)
- Linux system performance and usage activity monitoring tools -Sysstat (Linux)
- Simple and fast sorting (Programming)
- Drawing from the Android source code analysis View (Programming)
- To install Cinnamon desktop environment on your Ubuntu 14.04 / 12.04 (Linux)
- Linux simple commands (Linux)
- Nonstandard IMP-00010 error processing one case (Database)
- Oracle RMAN backups of the control file backup (Database)
- Mac Docker deploy development environment (Server)
- Linux iptables: combat scenes (Linux)
- RHEL (RedHat) 6.3 using EPEL Yum source (Linux)
- Linux installation JDK1.6 rpm.bin assembly (Linux)
- Construction CA certificate using OpenSSL command line (Server)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.