Home IT Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ AngularJS achieve picture upload feature     - Use Android Studio and Gradle packaged multi-version APK (Programming)

- Understanding Linux firewall Iptables (Linux)

- How to install Unbound and DNSCrypt in Archlinux (Server)

- Ubuntu 14.04 How to set up an SSH without password (Linux)

- Detailed usage history command (Linux)

- How to view the Linux QPS (Linux)

- Get the Linux device PCI ID method (Linux)

- Nginx introduced Dynamic Module Architecture (Server)

- How Glances monitoring system on Ubuntu (Linux)

- Java string equal size comparison (Programming)

- Spacewalk remove packages install the update (Linux)

- Python object-oriented programming (Programming)

- HTTP Client Hints Introduction (Server)

- CentOS7 install JAVA notes (Linux)

- NAT (network address translation) Realization (Linux)

- Justniffer installed on Ubuntu 15.04 (Linux)

- Ubuntu install Tonido private cloud services (Server)

- SQLite3 simple operation (Database)

- Apache2.4.7 make an error [exports.lo] Error 1 Solution (Server)

- Vim configuration instructions (Linux)

  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.
- Java 8 perspective annotation types (Programming)
- CentOS7 installation performance monitoring system (Server)
- RHEL6.5 install the latest version of Vim and increase support for the Python2.7.5 (Linux)
- Linux user opens a number of adjustment processes (Linux)
- Cacti monitoring service Nginx (Linux)
- CentOS system dual network card IP information configuration (Linux)
- Docker + OpenvSwitch build experimental environment VxLAN (Server)
- Hive handle count distinct inclination to produce data processing (Database)
- Commonly used Linux system camouflage method (Linux)
- C ++ type conversion and RTTI (Programming)
- Httpclient4.4 of principle (Http execution context) (Programming)
- Linux Getting Started Tutorial: How to set up a static MAC address on VMware ESXi virtual machine (Mobile)
- Debugging with GDB tool Go (Programming)
- Achieve camera preview by ffplay (Linux)
- Python virtual environment: Virtualenv (Linux)
- GNU / Linux system, how to clean up memory space (Linux)
- Oracle 11g + RAC + RHEL6.5 + udev + ASM + PSU installation summary (Database)
- Four Methods of Self - Learning Linux (Linux)
- grep regular expression (Linux)
- CentOS installed JDK8 (Linux)
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.