napfernandes
napfernandes

Reputation: 1359

ASP.NET MVC 3 - File upload through AngularJS

I'm using AngularJS with my pages, and I have a doubt: when I do post with my form, how can I pass some selected file to my ASP.NET MVC 3 Controller? Check this out:

My form:

<form enctype="multipart/form-data" ng-controller="FilesController" ng-submit="submitingForm()">
    <div>
        Choose the file:
        <input type="file" onchange="angular.element(this).scope().setSelectedFile(this)" />
    </div>

    <input type="submit" value="Confirm" />
</form>

And the AngularJS Controller:

var module = angular.module('application', []);

(function (ang, app) {

    function FilesController($scope, $http) {

        $scope.setSelectedFile = function (element) {
            $scope.$apply(function($scope) {
                $scope.selectedFile = element.files[0];
            });
        };

        $scope.submitingForm = function() {

            $http.post(url, ???????).success(function() {
                // How to pass that selected file for my ASP.NET controller?
            });
        }
    }

    app.controller("FilesController", FilesController);
})(angular, module);

Thank you!!!

Upvotes: 1

Views: 8543

Answers (2)

Moshi
Moshi

Reputation: 1423

My Approach is to use FormData.

Create a input tag like this.

<input id="imgInp" type="file" aria-label="Add photos to your post" class="upload" name="file" onchange="angular.element(this).scope().LoadFileData(this.files)" multiple="" accept="image/*" style="margin-top: -38px; opacity: 0; width: 28px;">

And in your Angular Controller create a method LoadFileData(inputFiles) as bellow:

 var formData = new FormData();

 $scope.LoadFileData = function (files) {
        for (var file in files) {
            formData.append("file", files[file]);
        }
    };

Now in formData variable you will have the uploaded files. Just send it to asp.net mvc controller.

$scope.submit = function () {
        $http.post("/YourController/Method", formData, {
            withCredentials: true,
            headers: { 'Content-Type': undefined },
            transformRequest: angular.identity
        }).success(function (response) {
      }

In Server side, Asp.NET MVC 4 controller you will have the files

var files = Request.Files;

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038840

I am not quite familiar with AngularJS but if you are attempting to upload a file using an AJAX request you can forget about it. That's not something that could be done. You could use the HTML5 File API if you want to upload files asynchronously to the server. There's an entire section dedicated to this.

And if your client browsers do not support the HTML5 File API you could use a File Upload plugin such as FineUploader or Uploadify (there are quite many others, just google).

Upvotes: 1

Related Questions