Friday, December 12, 2014

AngularJS Easiest way to upload a file

Here is the easiest way to include an upload file in your angular. This is not the angular way of doing the upload, but will get the work done. If you are doing a prototype or in a hurry, then you can use this approach.

I just have a simple view which allows user to select a file and upload it on a button click. Here is the view code.

    <div ng-controller="fileUploader">
        <input type="file" onchange="angular.element(this).scope().setFile(this)">
        <br />
        <button ng-click="UploadFile()">Upload</button>
    </div>

As you see in the above code, I defined a controller with a file input and button. On clicking the button will upload the file to the server.

Here is the angular script which sets the uploaded file to the scope and then uploads the file on the button click

'use strict';
angular.module('pos').controller('fileUploader', fileUploader)
fileUploader.$inject = ['$scope', '$http'];

function fileUploader($scope, $http) {
    $scope.setFile = function(element) {
        $scope.currentFile = element.files[0];
    }

    $scope.UploadFile = function () {
        var formData = new FormData();
        formData.append("file", $scope.currentFile);
        return $http.post("/api/user", formData, {
            headers: { 'Content-Type': undefined }, transformRequest: angular.identity
        });
    }
};


As mentioned above this is a hack solution. In my next blog I will rewrite this in an angular way by defining a directive and using it.

1 comment:

  1. hey,
    what is the format of the file when he send,
    can i add params to the function?

    ReplyDelete