Handling file uploads using AngularJS

Loading

What You’ll Learn

How to upload files using AngularJS
Using <input type="file"> for file selection
Handling file data in AngularJS controllers
Sending files to a server using $http
Using ngFileUpload for efficient file uploads


1️⃣ Basic File Upload Using <input type="file">

The simplest way to allow users to select files is by using the <input type="file"> element.

HTML Code

<div ng-app="myApp" ng-controller="UploadController">
<form>
<input type="file" file-model="myFile" />
<button ng-click="uploadFile()">Upload</button>
</form>
</div>

JavaScript Controller

var app = angular.module("myApp", []);

app.directive("fileModel", 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]);
});
});
},
};
});

app.controller("UploadController", function ($scope, $http) {
$scope.uploadFile = function () {
var file = $scope.myFile;
var formData = new FormData();
formData.append("file", file);

$http.post("/upload", formData, {
transformRequest: angular.identity,
headers: { "Content-Type": undefined },
}).then(
function (response) {
alert("File uploaded successfully!");
},
function (error) {
alert("File upload failed!");
}
);
};
});

How It Works:

  1. The file-model directive binds the file input to $scope.myFile.
  2. When a file is selected, it is assigned to $scope.myFile.
  3. uploadFile() creates a FormData object and appends the file.
  4. $http.post() sends the file to /upload with Content-Type: undefined.
  5. The server processes the uploaded file.

2️⃣ Using ngFileUpload for Advanced File Uploads

The ngFileUpload library simplifies file uploads and provides features like progress tracking, multiple file selection, and validation.

Install ngFileUpload

npm install ng-file-upload

or
Include the CDN in your HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/ng-file-upload/12.2.13/ng-file-upload.min.js"></script>

HTML Code

<div ng-app="myApp" ng-controller="UploadController">
<form>
<input type="file" ngf-select ng-model="file" name="file" />
<button ng-click="uploadFile(file)">Upload</button>
</form>
<p ng-show="progress >= 0">Upload Progress: {{progress}}%</p>
</div>

JavaScript Controller

var app = angular.module("myApp", ["ngFileUpload"]);

app.controller("UploadController", function ($scope, Upload) {
$scope.uploadFile = function (file) {
Upload.upload({
url: "/upload",
data: { file: file },
}).then(
function (response) {
alert("File uploaded successfully!");
},
function (error) {
alert("Upload failed!");
},
function (evt) {
$scope.progress = Math.min(100, parseInt((100.0 * evt.loaded) / evt.total));
}
);
};
});

Why Use ngFileUpload?

Simplifies file binding (ngf-select automatically binds file input)
Tracks progress (shows upload percentage)
Supports multiple file uploads


3️⃣ Validating File Size & Type Before Upload

With ngFileUpload, we can restrict file types and sizes easily.

HTML Code

<input type="file" ngf-select ng-model="file" 
ngf-pattern="'image/*'"
ngf-max-size="2MB" />
<p ng-show="file.$error">Invalid file! Please upload an image under 2MB.</p>
<button ng-click="uploadFile(file)">Upload</button>

How It Works:

  • ngf-pattern="'image/*'" allows only images
  • ngf-max-size="2MB" restricts file size to 2MB

4️⃣ Uploading Multiple Files

We can allow users to upload multiple files at once using ngf-multiple.

HTML Code

<input type="file" ngf-select ng-model="files" ngf-multiple="true" />
<button ng-click="uploadFiles(files)">Upload All</button>

JavaScript Controller

$scope.uploadFiles = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
$scope.uploadFile(files[i]);
}
}
};

How It Works:

Uses ngf-multiple="true" to allow multiple file selection
Loops through the files array and uploads each file


5️⃣ Handling File Upload Errors Gracefully

We can add error handling to inform users if the upload fails.

Modify uploadFile()

Upload.upload({
url: "/upload",
data: { file: file },
}).then(
function (response) {
alert("File uploaded successfully!");
},
function (error) {
if (error.status === 413) {
alert("File too large! Please upload a smaller file.");
} else {
alert("Upload failed! Please try again.");
}
}
);

How It Works:

✔️ Checks if error.status === 413 (HTTP status for “Payload Too Large”)
✔️ Displays an appropriate error message


6️⃣ Backend Setup (Node.js & Express Example)

In real-world apps, the server handles file uploads. Here’s a basic Node.js Express example.

Install Dependencies

npm install express multer

Backend Code (server.js)

const express = require("express");
const multer = require("multer");
const app = express();
const upload = multer({ dest: "uploads/" });

app.post("/upload", upload.single("file"), (req, res) => {
if (!req.file) {
return res.status(400).send("No file uploaded.");
}
res.send("File uploaded successfully!");
});

app.listen(3000, () => console.log("Server running on port 3000"));

How It Works:

  • Uses multer to handle file uploads
  • Saves uploaded files in the uploads/ folder

Leave a Reply

Your email address will not be published. Required fields are marked *