1

I am uploading image using input type file along with other user data. My model consists of the User class:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Rollno { get; set; }
    public byte[] ProfileImage { get; set; }
    public HttpPostedFile image { get; set; }
}

and a posted method in asp.net mvc:

public ActionResult AddUser(User user)
{
    var files = Request.Files;
    foreach (string fileName in Request.Files)
    {
        HttpPostedFileBase file = Request.Files[fileName];
        byte[] uploadFile = new byte[file.InputStream.Length];

    }
    return View();
}

I have an 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/*">

and an angularJS controller like this:

angular.module('app', ['AngularDemo.BeerController']).
  controller('formController',['$scope','$http', function ($scope,$http) {
    alert('in controller');
    var formData = new FormData();

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

    $scope.submit = function () {

        alert('in submit');
        $http.post("/Home/AddUser", formData, {
            withCredentials: true,
            headers: { 'Content-Type': undefined },
            transformRequest: angular.identity
        }).success(function (response) {

        });
    }
}]);

My image file is posting back in the AddUser method but how do I send the model data? I have added ng-model="Name" etc in the form. How do I send $scope.Name etc with that image data since my $http.post taking form data as passing data?

2 Answers 2

2

I got this fixed. The return was missing

.controller('formController',['$scope','$http', function ($scope, $http) {
 $scope.user = {
                 Id: 0,
                 Name: ""
               };
$scope.files = [];

$scope.LoadFileData = function(files) {
    $scope.files = files;
};

$scope.submit = function() {
    $http({
        url: "/Home/AddUser",
        method: "POST",
        headers: { "Content-Type": undefined },
        transformRequest: function(data) {
            var formData = new FormData();
            formData.append("user", angular.toJson(data.user));
            for (var i = 0; i < data.files.length; i++) {
                formData.append("files[" + i + "]", data.files[i]);
            }
            *return formData;*//NOTICE THIS RETURN WHICH WAS MISSING
        },
        data: { user: $scope.user, files: $scope.files }
    })
    .success(function(response) {   });
};
});
Sign up to request clarification or add additional context in comments.

1 Comment

did you get the model filled?
1

You can get this to work if you pass User as a JSON string. This won't bind the image properties of the User class, however.

[HttpPost]
public ActionResult AddUser(string user, HttpPostedFileBase[] files)
{
    // parse user into User
}

Form fields

<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/*">
<input name="Id" type="text" ng-model="user.Id" />
<input name="Name" type="text" ng-model="user.Name" />

And the Angular controller

.controller('formController',['$scope','$http', function ($scope, $http) {
    $scope.user = {
        Id: 0,
        Name: ""
    };
    $scope.files = [];

    $scope.LoadFileData = function(files) {
        $scope.files = files;
    };

    $scope.submit = function() {
        $http({
            url: "/Home/AddUser",
            method: "POST",
            headers: { "Content-Type": undefined },
            transformRequest: function(data) {
                var formData = new FormData();
                formData.append("user", angular.toJson(data.user));
                for (var i = 0; i < data.files.length; i++) {
                    formData.append("files[" + i + "]", data.files[i]);
                }
            },
            data: { user: $scope.user, files: $scope.files }
        })
        .success(function(response) {   });
    };
});

If you don't want to parse JSON to User then you'll have to write a custom binder. If there isn't a lot of user fields you might just pass them as discrete parameters.

public ActionResult AddUser(string userName, int userId, HttpPostedFileBase[] files) { ... }

5 Comments

It is giving null values for both image and user ,arguments are null when posted
Need help it is giving null values
Watch the request with the debugger's network monitor. You should see data posted there. You could be posting data but the binding will fail so it will appear as null in the action.
then what to do use Request ?
You don't need Request. Use the browser's debugger (usually F12) then make sure the network request is sending the data then make sure the names in your action match the key names in FormData. If you see data being sent then it's probably a problem with your parameter names not matching. If you don't see data sent then your angular code didn't form the request properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.