Thursday, March 19, 2015

Model for selecting file in angularJS

Create directive
 
gaMobileApp.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;
          
            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

Use directive

<input type="file" file-model="file1" />

Uploading multipart form in angularJS

//create formData first

$http.post(url, formData,
            {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            })
                .success(function(data, status, headers, config) {
                   
                })
                .error(function(data, status, headers, config) {
                          
           });

Convert datauri to blob - for uploading base64 data uri as image file

````
 function dataURItoBlob(dataURI, imgType) {
        var isSemicolonExist = (dataURI.indexOf(',') >= 0) ? true : false;
        alert(isSemicolonExist);
        var binary=[];
        if(isSemicolonExist)
            binary = atob(dataURI.split(',')[1]);
        else
            binary = atob(dataURI);
        var array = [];
        for(var i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
        }
        var blob = new Blob([new Uint8Array(array)], {type: imgType});
        return blob;
    }
````