jazza1000
jazza1000

Reputation: 4247

asp.net core file upload always null

I have been trying to follow this example in the documentation to allow a file to be uploaded to my controller, it does hit my action, but it always comes through as null.

My view model

<form method="post" enctype="multipart/form-data" asp-controller="Data" asp-action="ImportAdditionalCodes">
    <div class="form-group">
        <div class="col-md-10">
            <p>Upload import data:</p>
            <input type="file" name="files" >
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-10">
            <input type="submit" value="Upload">
            <button type="button" id="btnCancelUploadData">Cancel</button>
        </div>
    </div>
</form>

My Controller action

[HttpPost]
public async Task<IActionResult> ImportAdditionalCodes(IFormFile file)
{
    //file is always null here!!!
    if (file?.Length > 0)
    {
        JsonSerializer js = new JsonSerializer();
        using (MemoryStream ms = new MemoryStream())
        {
            await file.CopyToAsync(ms);

            using (StreamReader streamReader = new StreamReader(ms))
            {
                CommodityAdditionalCodeTypeDto[] codes= (CommodityAdditionalCodeTypeDto[]) js.Deserialize(streamReader, typeof(CommodityAdditionalCodeTypeDto[]));
            }
        }
   }
   return null;
}

Upvotes: 2

Views: 3289

Answers (2)

Sadikul Haque Sadi
Sadikul Haque Sadi

Reputation: 579

You can also skip the name attribute inside input tag. Like this -

<input asp-for="MyFile">

Where the corresponding ViewModel is

public class FileUploadViewModel
{
    public IFormFile MyFile{ get; set; }
}

It will know that input type is file (seeing the IFormFile type) and will automatically add name attribute to "MyFile".

Upvotes: 1

Piotr Stapp
Piotr Stapp

Reputation: 19830

Small typo. Instead of

<input type="file" name="files" >

Write:

<input type="file" name="file" >

You can also access send files using HttpContext.Request.Form.Files;

Upvotes: 6

Related Questions