Implementation of AngularJS Image Upload Function

Source: Internet
Author: User

Implementation of AngularJS Image Upload Function
I. Preface when I was working on a project some time ago, I encountered a problem: AngularJS implemented the image preview and upload function. At that time, I had to go through the document (both in English) for a long time, now we will sort out the entire process. If you have any need, please refer to it. If you have a better method, please leave a message to us ~~ Let's just look at the implementation. II. Specific implementation 1. html tag structure <input type = "file" file-model = "myFile"/> <div class = "col-md-12"> </div> input File Upload tag, the img label of the div package is the image preview area. 2. Define direve ve.

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]) ;}); // preview the scope. file = (event. srcElement | event.tar get ). files [0]; scope. getFile () ;}}};}]);

 

The attribute file-model in the input tag is the instruction in Angular. In the link Method of the code above, we bound the change event to the element where the command file-model is located, get the file object to be uploaded in the change method, and call the getFile () method in controller (See controller) 3. Define the controller UploaderControler to copy the angular code. module ('app '). controller ('uploadercontroller', function ($ scope, fileReader) {$ scope. getFile = function () {fileReader. readAsDataUrl ($ scope. file, $ scope ). then (function (result) {$ scope. imageSrc = result;}) ;};}) replace The Code controller defines an UploaderController, which defines the getFile () method in its scope. the getFile method calls the readAsDataUrl method in the fileReader service, in this method, the url of the image is generated, the result is returned to getFile, and the returned url is assigned to $ scope. imageSrc: According to the Angular bidirectional data binding mechanism, if the ng-src attribute value in the img element is url, You can preview the image 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) {                    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 is mainly used to generate the url address of the obtained file and return it to the view for preview. 5. Implement attachment upload: Upload the page form data to the database through the interface provided by the background. Add the following code to the Controller UploaderControler:
// Assemble 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 is the data in the form (including the uploaded image information). '/maldives/leave/save' indicates the data interface in the request background, and $ http is the Angular built-in service, can send GET or POST requests to the background. 3. Understanding and understanding of service, controller, and ctive VE in Angular is an alias of a singleton object in AngluarJS. These Singleton objects will be transmitted frequently to ensure that each time you access the same instance. Based on this idea, the singleton object allows us to implement some cool functions, which allows many controllers and ctive ve to access their internal values. The controller concatenates services, dependencies, and other objects, and then associates them with the view through scope. If you need to process complex business logic in your view, putting them in the controller is also a very good choice.

Related Article

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.