ng-file Upload Angular js

Saloni Malhotra
Aug 29, 2017 · 2 min read

Lightweight Angular directive to upload files.Follow the steps written below to upload Single or Multiple Files in Angular js.

First Step:- npm install
npm install ng-file-upload

Second Step :- Include the scripts in your main html or in routing file
<script src=”ng-file-upload-shim(.min).js”></script>
<script src=”ng-file-upload(.min).js”></script>

Third Step :- HTML text

<form ng-app="fileUpload" ng-controller="fileCtrl" name="form">
<--Single Image with validations-->
<div class="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'" ngf-accept="'image/*'" ngf-max-size="20MB" ngf-min-height="100">Select</div>
<--Single Image with validations-->

<--Multiple Image with validations-->
<div class="button" ngf-select ng-model="files" ngf-multiple="true">Select</div>
Drop files: <div ngf-drop ng-model="files" class="drop-box">Drop</div>
<--Multiple Image with validations-->
<button type="submit" ng-click="submit()">submit</button>
</form>

Fourth Step:-

//inject directives and services.
var app = angular.module('fileUpload', ['ngFileUpload']);

app.controller('fileCtrl', ['$scope', 'Upload', function ($scope, Upload) {
$scope.submit = function() {
if ($scope.form.file.$valid && $scope.file) {
$scope.upload($scope.file);
}
};
// upload on file select or drop
$scope.upload = function (file) {
Upload.upload({
url: 'upload/url',
data: {file: file}
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
});
};
// for multiple files:
$scope.uploadFiles = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
Upload.upload({..., data: {file: files[i]}, ...})...;
}

Upload.upload({..., data: {file: files}, ...})...;
}
}
}]);

Hi, My name is Saloni Malhotra. I am a Javascript Developer and writer. I am here to talk so Don’t hesitate to Drop me a message.if you like my story Please Click ❤ and share with everyone.

Thanks !!
Happy coding

)

Written by

I write about web development, Answers questions on Quora. Solving people problems using code spells. Web developer, Writer, Thinker.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade