,

Uploading Files with jQuery and AngularJS

Posted by


In this tutorial, we will be discussing how to implement file uploads using jQuery and AngularJS. File uploads are a common feature in web applications, as they allow users to upload files such as images, documents, and videos.

First, we will need to include the necessary libraries in our project. Make sure to include the jQuery and AngularJS libraries using the following script tags in your HTML file:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>

Next, we will create an HTML form with an input element of type file for users to select files they want to upload. Here is an example of a basic form for file uploads:

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

In the form above, we have used AngularJS directives like ng-app, ng-controller, ng-click, and file-model. The file-model directive is a custom directive that we will define in our JavaScript file to handle file uploads.

Now, let’s define the custom directive fileModel in our JavaScript file:

var app = angular.module('fileUploadApp', []);

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]);
        });
      });
    }
  };
}]);

app.controller('FileUploadCtrl', ['$scope', '$http', function ($scope, $http) {
  $scope.uploadFile = function () {
    var file = $scope.myFile;

    var fd = new FormData();
    fd.append('file', file);

    $http.post('/upload', fd, {
      transformRequest: angular.identity,
      headers: { 'Content-Type': undefined }
    })
      .then(function (response) {
        console.log(response.data);
      })
      .catch(function (error) {
        console.error(error);
      });
  };
}]);

In the code above, we have defined a directive called fileModel that binds the selected file to a scope variable. This scope variable is then used in the FileUploadCtrl controller to upload the file using AngularJS’s $http service.

In the uploadFile function, we create a new FormData object and append the selected file to it. We then make a POST request to the server with the file data using AngularJS’s $http.post method. The transformRequest property is set to angular.identity to prevent AngularJS from serializing the FormData object, and the Content-Type header is set to undefined to let AngularJS handle the content type automatically.

Lastly, we need to handle the file upload on the server-side. You can use any server-side technology for this, such as Node.js, Python, PHP, etc. Here is an example using Node.js and Express:

const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');

const app = express();
const upload = multer();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/upload', upload.single('file'), (req, res) => {
  const file = req.file;

  if (!file) {
    return res.status(400).send('No file uploaded');
  }

  res.send('File uploaded successfully');
});

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

In the server-side code above, we have used Express.js to handle POST requests to the /upload endpoint. We use multer middleware to parse the uploaded file, which is accessible via req.file. If no file is uploaded, we return a 400 Bad Request response. Otherwise, we send a 200 OK response indicating that the file has been uploaded successfully.

That’s it! You now have a basic file upload system using jQuery and AngularJS. Feel free to enhance this system by adding features like file validation, progress bars, multiple file uploads, etc.