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,

$'/path/of/request', fd, {
     headers: { 'Content-Type': undefined},
     transformRequest: angular.identity
   }).success(function (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.