File Upload Not Working

Kmcnet 946 Reputation points
2023-05-18T21:08:37.9966667+00:00

Hello everyone and thanks for the help in advance. I am refactoring a file upload application, but can't get it working:

My HTML:


<form enctype="multipart/form-data" method="post" action="UploadFiles">
    <dl>
        <dt>
            <label></label>
        </dt>
        <dd>
            <input type="file" name="file" id="file" />
            <span></span>
        </dd>
    </dl>
    <input type="submit" value="Upload" />
</form>

My Controller


        [HttpPost]
        public IActionResult UploadFiles(List<IFormFile> postedFiles)
        {

            return Content("Count=" + postedFiles.Count.ToString());

        }

Returns 0. What am I doing wrong?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,777 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,593 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 29,781 Reputation points
    2023-05-18T21:49:39.25+00:00

    What am I doing wrong?

    • The action path.
    • File element name does not match action parameter name.
    • The file element is missing the multiple attribute.
            public ActionResult Index()
            {
                return View();
            }
    
            [HttpPost]
            // FileUpload/UploadFiles
            public IActionResult UploadFiles(List<IFormFile> postedFiles)
            {
                return Content("Count=" + postedFiles.Count.ToString());
            }
    
    
    @{
        ViewData["Title"] = "Index";
    }
    
    <h1>Index</h1>
    
    <div>
        <form enctype="multipart/form-data" method="post" action="/FileUpload/UploadFiles">
            <dl>
                <dt>
                    <label></label>
                </dt>
                <dd>
                    <input type="file" name="postedFiles" id="file" multiple />
                    <span></span>
                </dd>
            </dl>
            <input type="submit" value="Upload" />
        </form>
    </div>
    

    Reference documentation

    Upload files in ASP.NET Core


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.