Wednesday, May 18, 2016

File Upload with Angular

HTML5 offers some cool features for uploading files, including the ability to drag and drop a file from your computer onto an area of the web page and have that file uploaded.  But Angular doesn't come with a built-in way to do it.  Fortunately (and this is one of the reasons I love Angular so much) there's already a community-built, open-source directive available for just that.  Actually, there are a lot of them, but I picked one in particular and it's working pretty well so far.  The one I picked is called ng-file-upload and can be found here.

That's great and all, but it didn't quite get me all the way to where I needed to be.  For that I needed another post, found here.  In that post the author explains how to structure the request with a FormData object.  It boils down to this:
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
    transformRequest: angular.identity,
    headers: {'Content-Type': undefined}
});
You can put that in the watch (though you should really abstract it into a service) on 'file' (or whatever your scope variable is that's bound to ng-model of ng-file-upload) and you'll be able to upload the file correctly.  I had to add a few other things, like usingangular.toJson(item)to stringify an object as part of the parameter to the server, but that's specific to my implementation. The above code should be enough to have a drag and drop feature that does what you need in a basic use case.

No comments:

Post a Comment