File Upload with AngularJS and NodeJS

Uploading files is a common feature that is often required in web applications. In this tutorial, we will guide you through the process of creating a file upload feature using AngularJS on the front-end and Node.js on the back-end.

Setting Up Your Environment

Before we begin, ensure that you have Node.js and AngularJS installed on your machine. If not, you can download Node.js from the official Node.js website and AngularJS from the official AngularJS website.

Next, we’ll need to install a few Node.js modules:

  • Express: A fast, unopinionated, and flexible web application framework for Node.js.
  • Multer: A middleware for handling multipart/form-data, which is primarily used for uploading files.

You can install these modules using npm (Node Package Manager) with the following command:

npm install express multer

Creating the Server

First, we’ll create a simple Express server. Create a new file named server.js and add the following code:

var express = require('express');
var multer  = require('multer');
var upload = multer({ dest: 'uploads/' });

var app = express();

app.post('/upload', upload.single('file'), function (req, res, next) {
  // req.file is the `file` file
  // req.body will hold the text fields, if there were any
  res.send('File uploaded successfully!');
});

app.listen(3000, function () {
  console.log('Server listening on port 3000!');
});

This code sets up an Express server that listens for POST requests at the /upload endpoint. When a request is received, the Multer middleware processes the file upload and saves the file to the uploads/ directory.

Creating the Front-End

Next, we’ll create a simple AngularJS application that allows the user to select a file and upload it to the server. Create a new HTML file named index.html and add the following code:

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="myApp">

<div ng-controller="myCtrl">
  <input type="file" id="file" name="file" ng-model="file" file-model="file" />
  <button ng-click="uploadFile()">Upload</button>
</div>

<script>
var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope, $http) {
  $scope.uploadFile = function() {
    var file = $scope.file;
    var fd = new FormData();
    fd.append('file', file);

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

app.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]);
        });
      });
    }
  };
}]);
</script>

</body>
</html>

This code sets up an AngularJS application that includes a file input and an upload button. When the upload button is clicked, the selected file is sent to the server using the $http service.

Testing the Application

To test the application, start the server by running node server.js in your terminal. Then, open index.html in your web browser. Select a file using the file input, then click the upload button. If everything is set up correctly, you should see the message ‘File uploaded successfully!’, and the file should be saved in the uploads/ directory on your server.

This tutorial provides a basic introduction to creating a file upload feature using AngularJS and Node.js.

Facebook
Twitter
LinkedIn
Pinterest

Table of Contents

Related posts

AngularJS Directives

In the landscape of JavaScript frameworks, AngularJS stands out for its feature-rich nature and comprehensive solution for building web applications.

Read More