Home IT Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ AngularJS achieve picture upload feature     - Installation image conversion tool on your Ubuntu Converseen 0.8.1 (Linux)

- MySQL tmpdir parameter modification (Database)

- Build RPM package uses Docker mirror (Linux)

- Java semaphores (Programming)

- How to find on Linux and delete duplicate files: FSlint (Linux)

- Linux variable learning experience (Linux)

- MySQL Basic tutorial: About varchar (N) (Database)

- Graphical interface for the CentOS 6.4 installed and connected by remote VNC (Linux)

- To install and deploy Apache under the CentOS (Server)

- iTerm - let your command line can also be colorful (Linux)

- Transfer MySQL database to MariaDB (Database)

- Oracle users to automatically increase the partition table (Database)

- CentOS 6 compiling httpd-2.4.10 (Server)

- CentOS How to mount the hard drive (Linux)

- Open log in Hibernate (Programming)

- Secondary exponential smoothing prediction method implemented in Python (Programming)

- Linux system security reinforcement system by masquerading method (Linux)

- Method under Linux GCC Compiler shared library function export control (Programming)

- Help you enhance Python programming languages 27 (Programming)

- Ubuntu Tutorial: How to Upgrade a New Linux Kernel 3.12.7 on Ubuntu (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.
- How to use the TF / SD card making Exynos 4412 u-boot boot disk in Ubuntu (Linux)
- How to implement Linux host Telnet SSH password Free (Server)
- Oracle index visible and hidden (visible / invisible) (Database)
- ssh port forwarding Comments (Server)
- Linux performance optimization features Tuned and ktune (Linux)
- Linux System Getting Started Learning: From VirtualBox from the client host access NAT (Linux)
- DM9000 timing settings (Programming)
- Mac OS X systems create Ubuntu USB boot disk for the Mac (Linux)
- Use PuTTY key authentication mechanism for remote login Linux (Linux)
- ASP.NET 5 tutorial series (Server)
- Installation and configuration under Linux SVN server - Backup - Recovery - Scheduled Tasks (Server)
- How to modify the Emacs Major Mode Shortcuts (Linux)
- Oracle SQL statement tracking (Database)
- Install multiple Linux distributions and Fedora 21 first experience on the same hard disk (Linux)
- MongoDB Installation under CentOS 6.6 (Database)
- Getting Started with Linux: CentOS7 Install Mono with the yum command (Server)
- Dual system Linux (Ubuntu) into the Windows NTFS partition's mount error (Linux)
- Redhat 5 prohibit IPv6 (Linux)
- Linux (Ubuntu) How iptables port mapping (Server)
- VMware difference in three network connection (Linux)
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.