Implementation of ANGULARJS image upload function

Source: Internet
Author: User

Original http://www.cnblogs.com/changjianqiu/p/4678153.html

First, preface

A period of time to do the project, encountered a problem is ANGULARJS implementation of the image preview and upload function, at that time to check the document (all English documents) toss a long time to get out, will be the whole process of sorting out, there is a need for friends can refer to, if you have a better method, welcome message exchange ~ ~ Words do not say more directly see the realization.

Second, the concrete realization

1. HTML tag structure

<type=file-model="MyFile"/><class=<ng-src=style=" max-width:300px;max-height:300px;margin:0 auto;display:block; "/></div>   

Input file upload tag, div package img tag for picture preview area

2. define directive

Angular.module (' app '). Directive (' Filemodel ', [' $parse ',function ($parse) { return { Restrict' A ', Linkfunction (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]);    });     // accessories preview Span class= "indent" >     Scope.file = (Event.srcelement | | event.target). Files[0];    Scope.getfile ();    }};});        

The attribute File-model in the input tag is the instruction in angular, in the link method of the above code, we bind the change event to the element where the instruction File-model is located, and the change method obtains the file object to be uploaded. and called the GetFile () method in the controller (see Controller)

3, define the controller Uploadercontroler

Angular.module ('app ')            . Controller (' Uploadercontroller ', function ($scope, FileReader) {                 function() {Filereader.readasdataurl ($scope. imagesrc = result;});};})     

A uploadercontroller is defined in the controller that defines the GetFile () method in its scope, and the Readasdataurl method in the FileReader service is called in the GetFile method. This method generates the address URL of the picture, returns the result to GetFile, assigns the returned URL to $scope.imagesrc, and according to the mechanism of angular bidirectional data binding, the NG-SRC attribute value in the IMG element is the URL, so you can preview the picture on the page. How is the FileReader service defined?

4. Define Service FileReader

Angular.module (' app '). Factory (' FileReader ', ["$q","$log", function ($q,$log) { var onLoad = function (reader, deferred, scope) {  Returnfunction () {  Scope.$apply (function () {   Deferred.resolve (Reader.result);  }); };}; var onError =function (Reader, deferred, scope) {  Returnfunction () {  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) {  span class= "keyword" >var deferred =  $q. defer ();   var reader = Getreader (deferred, scope);   Reader.readasdataurl (file);   return deferred.promise;};  return {  Readasdataurl: Readasdataurl };}])            

The FileReader service mainly completes the URL of the generated file and returns to the view for preview.

5, the implementation of attachment upload

Attachment upload is mainly to write the page form data through the interface provided by the background to the database, the implementation of the Controller Uploadercontroler add the following code:

        //Assemble form datavar 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 (); foreach (data, function (Val, key) {  Fd.append (Key, Val);  var args = {  method:  ' POST ',   Url:url,  Data:fd,  headers: { ' Content-type ': undefined},< Span class= "indent" >  Transformrequest:angular.identity}; return  $http (args);        

PostData is the data in the form (including uploaded picture information), '/maldives/leave/save ' represents the data interface of the request background, $http is the angular built-in service, can send a GET or POST request to the background.

Iii. Understanding and understanding of service, controller and Directive in angular

A service is an alias for a singleton object in Angluarjs. These singleton objects are often transmitted to ensure that every time you access the same instance. Based on this idea, a singleton object allows us to implement some pretty cool features that allow many controllers and directive to access their internal values.

The controller concatenates the service, dependencies, and other objects together, and then associates them to the view through scope. If you need to deal with complex business logic in your view, it's also a good idea to put them in the controller.

Angular's definition of directive is a snippet of code that you can use to manipulate the DOM, or it can be used for user interaction.

Implementation of ANGULARJS image upload function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.