0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.