Friday, January 11, 2013

File Upload using AngularJs

Although AngularJs does not support file upload, as of now, there are several ways to achieve it using the input tag.

One method is to integrate file upload plugins. An alternative to that is sending form-data.

Sending form data is simple,

$http.post('/path/of/request', fd, {
     headers: { 'Content-Type': undefined},
     transformRequest: angular.identity
   }).success(function (result) {
     alert(result);
   });

where fd is a FormData Object.

The file can be set using the files property of the input element.

We could also use XMLHTTPRequest to upload a file. Link to a simple component to upload a file

In this directive, component is an angular module and it can simply be used by having a 'fileUpload' tag.

Note: This doesn't work in older versions of IE where there is no FormData object. Those interested can check stackoverflow or filepicker.

7 comments:

  1. Hi

    Thanks for sharing this but it do not works with internet explorer 8 & below.

    ReplyDelete
  2. FormData doesn't work for IE < 10.

    :(

    ReplyDelete
  3. HI, I'm trying it:

    $scope.submit = function(){
    $http.post($scope.serviceSave, $scope.file, {
    headers: {'Content-Type': undefined},
    transformRequest: angular.identity
    }


    form ng-submit="submit()"
    input type="file" id="foto" ng-model="file"
    input type="submit" class="btn" value="go"
    /form

    what's wrong?

    ReplyDelete
    Replies
    1. It would be better if you posted all the relevant functions.
      One of the things may be that you don't have something like setFile() function.
      You need to set the file manually as file input is not handled in AngularJs.

      Delete
  4. Hey, it's really nice and simple. Is it possible to add progress bar to this?

    ReplyDelete
    Replies
    1. You could do that in a custom directive, I have updated the blog, the gist wasn't visible in dynamic theme.

      You could refer to
      https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest?redirectlocale=en-%20US&redirectslug=DOM%2FXMLHttpRequest%2FUsing_XMLHttpRequest#Monitoring_progress

      The progress is set as the width of a div element.
      You might find this question from stackoverflow also quite helpful.
      http://stackoverflow.com/questions/76976/how-to-get-progress-from-xmlhttprequest

      Delete

Note: Only a member of this blog may post a comment.