upload file in angular with own directive

(In order to Enlarge images Please Right Click and Open images in New Tab).

 

2

 

j1

 

 

Code-

<input type=”text” class=”form-control” ng-model=”filePath” ng-file-select=”onFileSelect($files)” ng-disabled=”isBrowseDisabled”>
<label class=”input-group-btn”>
<span class=”btn btn-primary”>
Browse <input type=”file” style=”display: none;” ng-file-select=”onFileSelect($files)” ng-disabled=”isBrowseDisabled”>
</span>
</label>

 

j2

 

 

Code-

 

app.directive(“ngFileSelect“, function () {
return {
link: function ($scope, el) {
el.bind(“change”, function (e) {
$scope.file = (e.srcElement || e.target).files[0];
var path = e.target.value;
path = path.substring(0, 3);
$scope.filePath = path + $scope.file.name;
//$scope.filePath = e.target.value;
$scope.getFile();
})
}
}
})

 

 

Controller.js

j3

$scope.onLoad = function (reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.resolve(reader.result);
});
};
};
$scope.onError = function (reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.reject(reader.result);
});
};
};
$scope.onProgress = function (reader, scope) {
return function (event) {
scope.$broadcast(“fileProgress”,
{
total: event.total,
loaded: event.loaded
});
};
};
$scope.getReader = function (deferred, scope) {
var reader = new FileReader();
reader.onload = $scope.onLoad(reader, deferred, scope);
reader.onerror = $scope.onError(reader, deferred, scope);
reader.onprogress = $scope.onProgress(reader, scope);
return reader;
};
$scope.readAsDataURL = function (file, scope) {
var deferred = $q.defer();
var reader = $scope.getReader(deferred, scope);
reader.readAsDataURL(file);
return deferred.promise;
};

 

j4

 

$scope.getFile = function () {
$scope.progress = 0;
$scope.readAsDataURL($scope.file, $scope)
.then(function (result) {
$scope.xslData = result; // resultĀ This is Binary Data
$scope.uploadedDocName = $scope.file.name;
$scope.fileInfodetails = “File name: ” + $scope.filePath + ” ” + $scope.file.size + ” ” + “Bytes”;
//$scope.fileDetails = $scope.filePath;
});
};

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s