Home IT Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ AngularJS achieve picture upload feature     - Linux Shell Understanding and Learning (Linux)

- Ubuntu 15.04 installation Powercommands 2.0 (Linux)

- Java polymorphic methods inside constructors complete analysis (Programming)

- After you change the GRUB boot disk partition repair (Linux)

- MySQL Server Time Synchronization Problem (Database)

- CentOS card fails to start at boot progress bar certmonger solve (Linux)

- Linux disk partition, format, mount the directory (Linux)

- Eclipse 3.7.2 can not start solving under Ubuntu 14.04 (Linux)

- CentOS 6.5 x86_64 system customized automated deployment (Linux)

- Linux Command - ps: a snapshot of the current process (Linux)

- Empty password Linux operating system (Linux)

- In-depth understanding of PHP ini configuration (Server)

- How to disable UEFI to install Linux on Win8 (Linux)

- Linux alpine use the command line to access Gmail (Linux)

- Two minutes thoroughly so that you understand Android Activity Lifecycle (Programming)

- SecureCRT remote connection Ubuntu fails to solve the case (Linux)

- How to Set Free SSH password on CentOS / RHEL (Linux)

- iOS9 new feature - stacked view UIStackView (Programming)

- Installation of Python2.7.8 and iPython under CentOS6.5 (Linux)

- MySQL EXPLAIN SQL output description (Database)

  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.
- How to Install Telegram instant messaging software on Ubuntu (Linux)
- RedHat Linux 7 build yum source server (Server)
- Gnu Linux - Ubuntu System Clean-term consolidation (Linux)
- Java and Python use make way dictionary word search script (Programming)
- C # get the current screenshot (Programming)
- Using a proxy method under Linux terminal (Linux)
- tespeed - test speed of Python tools (Linux)
- floating IP in OpenStack neutron (Server)
- Linux System Getting Started Learning: modify environment variables in Linux PATH (Linux)
- CentOS7 install MySQL5.6.22 (Linux)
- Java-- get the reflection object information (Programming)
- Ubuntu 15.04 install Complete Guide (Linux)
- Android project and coding specifications (Programming)
- Define and modify strings principle in Python (Programming)
- Linux kernel IPv6 protocol closed manner (Linux)
- How to achieve SSH without password login (Server)
- Ubuntu uses conky add desktop control (Linux)
- Git Advanced Tutorial (Linux)
- Linux System Getting Started Learning: DeVeDe installed on Linux to create a video DVD (Linux)
- Linux disk partition batch format mount script (Linux)
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.