2

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;
}
1

2 Answers 2

6

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;

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

Comments

1

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".

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.