Nathan Goings
Nathan Goings

Reputation: 1164

HttpPostedFileBase always null on file upload, model bound error

I'm trying to upload a file via JQuery Ajax to an ASP.NET Core MVC application.

The HttpPostedFileBase is always null. When I put it as a parameter directly in the action I'm getting a model bound error.

Javascript:

$(document).on('click', '#attachItemBtn', function () {
    var attachItemFiles = document.getElementById('attachItemFile');

    var formData = new FormData();
    formData.append("Document", attachItemFiles.files[0]);
    formData.append("Id", 1234);
    formData.append("FileName", "test");

    $.ajax({
        cache: false,
        type: "POST",
        data: formData,
        processData: false,
        contentType: 'multipart/form-data',
        url: App.Urls.AddAttachment,
        success: function (data) {
            App.Messages.showErrorMessage('Item attached');
        },
        error: function (xhr, ajaxOptions, thrownError) {
            App.Messages.showErrorMessage('Error Occured While attaching document');
        }
    });

    var debug = 0;
});

Action:

[HttpPost]
public IActionResult AddAttachment(AttachmentItemModel model)
{
    var count = HttpContext.Request.Form.Files.Count;
    int i = 0;
    return Json("done");
}

Model:

public class AttachmentItemModel
{
    public int Id { get; set; }
    public HttpPostedFileBase Document { get; set; }
    public string FileName { get; set; }
}

The above code works with HttpContext.Request.Form.Files but the model.Document is null

When I re-write the Action to the below function signature I get an error:

public IActionResult AddAttachment(int Id, string FileName, System.Web.HttpPostedFileBase Document)

I then get the below error:

An unhandled exception occurred while processing the request. InvalidOperationException: Could not create an instance of type 'System.Web.HttpPostedFileBase'. Model bound complex types must not be abstract or value types and must have a parameterless constructor.

What am I missing? I would prefer the file(s) be bound in my model instead of using HttpContext.Request.Files.

Upvotes: 2

Views: 684

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239300

How'd you even get HttpPostedFileBase to resolve? Regardless, it doesn't exist in ASP.NET Core. Instead, you should be using IFormFile.

Upvotes: 5

Related Questions