Tracking fileupload using XMLHttpRequest events

XMLHttpRequest gives us a way to send a request to a url and get the response without doing a full page refresh. For doing so, we have to follow three simple steps.

First, create an instance object of XHR. Secondly, open the request by providing the type(get or post) and the url. And last, sending the request with or without some data.

Some of the usefull methods are:

  • xhr.onLoad()
  • xhr.open()
  • xhr.onerror()
  • xhr.send()

In one of my projects, I used it to upload a file on server and track the percentage of uploaded data to show a progress bar to the user. AngularJS was used at the frontend and the code for uploading the file was written in one of the controllers.

Lets say, we have a method $scope.uploadFile() which is called to upload file to server.

$scope.uploadFile = function (evt) {
$scope.uploadProgressPercentage = 0;

var fd = new FormData();
fd.append('media', $scope.fileChosen);

var xhr = new XMLHttpRequest;
xhr.upload.onprogress = function (e) {
    console.log("Progress");
    $scope.uploadProgressPercentage = (e.loaded / e.total) * 100;
    $scope.$apply();
};
xhr.upload.onload = function (e) {
    //perform certain task
};
xhr.upload.onerror = function (e) {
    //perform certain task
};

xhr.open("POST", "/data/postMedia");
xhr.send(fd);
};

Firstly, we have created an instance of object of XHR and have opened a "POST" request connection to the provided url. We then append the file to the form data object and send it with the request.

In order to track the progress of file upload, we have an event xhr.upload.onprogress(), the method provides us a callback function in which we get an argument, using which we calculate the percentage of upload data.

In this way we can use XHR to retrieve or send any type of data, not just XML.

comments powered by Disqus