Search code examples
angularjsmodel-view-controllerfile-uploadhttppostedfilebase

HttpPostedFileBase is null - Posting files from AngularJS to MVC


Similar questions have been asked so many times, but there are no clear answers, I still have trouble getting mine to work.

This is the model in C#

public class SubmitModel
{
    public string Name { get; set; }
    public HttpPostedFileBase File { get; set; }
    public IEnumerable<HttpPostedFileBase> Files { get; set; }
}

This is the MVC code

[HttpPost]
public ActionResult Test(SubmitModel model)
{
    // Here model.File and model.Files is always null
}

This is what I submitted using AngularJS

var data = {
    name: scope.name,     // This is passed to MVC successfully
    file: scope.files[0], // Doesn't even work with single file
    files: scope.files    // This is a FileList
};
$http.post("/umbraco/surface/MyController/Test", data).success(...);

If you want to know how I assign scope.files:

$('#upload').on('change', function (e) {
    scope.$apply(function () {
        scope.files = e.target.files;
    });
});

Could someone see what I am missing?


Solution

  • Solved it!

    This is how it should be submitted

    var data = new FormData();
    angular.forEach(scope.item, function (value, key) {
        if (key == "files") {
            for (var i = 0; i < value.length; i++) {
                data.append(value[i].name, value[i]); // Filename:File
            }
        } else {
            data.append(key, value);
        }
    });
    
    $http.post("/umbraco/surface/MyController/Test", data, {
                    transformRequest: angular.identity,
                    headers: { 'Content-Type': undefined }
                }).success(...);
    

    Then in MVC, we get the files from Request.Files, it won't be in the model.

    [HttpPost]
    public ActionResult Test(SubmitModel model)
    {
        var files = Request.Files;  // a collection of HttpPostedFileBase
        Save(model, files);
    }
    

    More info:
    https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
    http://www.codeproject.com/Tips/878730/File-Upload-Using-AngularJS-and-ASP-NET-MVC