File uploads in ASP.NET Core

Just wrote down something I had to went through with students in one of my classes – making file uploads work in ASP.NET Core application. Here are samples of single and multiple file uploads using simple controller actions.

Creating upload action and view

I start with clean ASP.NET Core application and add Upload() action to HomeController.

public IActionResult Upload()
{
    return View();
}

It’s empty and returns just view to upload files.

Next thing is to create Upload view with following markup:

<h1>File upload</h1>

@*
    To post files to server we need form with post method,
    and additionally browser must use multipart/form-data
    encoding. Otherwise file will not be sent.
*@
<form method="post" enctype="multipart/form-data">
    <input type="file" name="file" /> 
    <button type="submit">Upload</button>
</form>

@*
    If upload succeeded we will show nice message to user.
*@
@if(ViewBag.Message != null)
{
    <div class="alert alert-success" style="margin-top:20px">
        @ViewBag.Message
    </div>
}

Saving uploaded file

To save file in server we need another controller action in HomeController. I name it again Upload() but this one is a little different.

[HttpPost]
public IActionResult Upload(IFormFile file)
{
    // Extract file name from whatever was posted by browser
    var fileName = System.IO.Path.GetFileName(file.FileName);

    // If file with same name exists delete it
    if(System.IO.File.Exists(fileName))
    {
        System.IO.File.Delete(fileName);
    }

    // Create new local file and copy contents of uploaded file
    using(var localFile = System.IO.File.OpenWrite(fileName))
    using(var uploadedFile = file.OpenReadStream())
    {
        uploadedFile.CopyTo(localFile);
    }

    ViewBag.Message = "File successfully uploaded";

    return View();
}

Notice [HttpPost] attribute on top of new Upload() action – it tells ASP.NET to use this action when browser makes POST request to Upload() method. New Upload() method has also argument named as file. Take a look at view markup above – we named file upload field as file too. ASP.NET will match these two automatically for us.

Uploading multiple files

To upload multiple files we doesn’t necessarily need multiple file upload fields. We can use one field for multiple files. For this to happen we need to add “multiple” attribute to file field. Also I will change name of file upload field from “file” to “files”.

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

Our file field works now with one file and multiple files.

We need to reflect this also in Upload() action. The change is simple – we just change method argument from single file to array and save files down in foreach loop.

[HttpPost]
public IActionResult Upload(IFormFile[] files)
{
    // Iterate through uploaded files array
    foreach (var file in files)
    {
        // Extract file name from whatever was posted by browser
        var fileName = System.IO.Path.GetFileName(file.FileName);

        // If file with same name exists delete it
        if (System.IO.File.Exists(fileName))
        {
            System.IO.File.Delete(fileName);
        }

        // Create new local file and copy contents of uploaded file
        using (var localFile = System.IO.File.OpenWrite(fileName))
        using (var uploadedFile = file.OpenReadStream())
        {
            uploadedFile.CopyTo(localFile);
        }
    }

    ViewBag.Message = "Files successfully uploaded";

    return View();
}

This is all we need to do to upload multiple files.

NB! To try file uploads out, run application in browser and type Home/Upload/ to the end of address. Browser will show upload view. Select some files from computer to upload and click Upload button. Uploaded files will be visible in Visual Studio solution explorer after successful upload.

Wrapping up

Handling file uploads in ASP.NET Core is easy. It’s easier than it was with previous ASP.NET versions. We just use IFormFile as upload method argument and ASP.NET Core puts uploaded file or files there. It’s easy to work also with multiple files – we can use array of IFormFile and iterate through it using foreach loop. It’s simple, clean and nice.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    39 thoughts on “File uploads in ASP.NET Core

    • November 4, 2019 at 11:21 am
      Permalink

      It should be noted that you should not use the file name for storing files locally as in your example. An attacker could delete files on the web server by crafting a file name that matches an existing file on the server.

    • November 4, 2019 at 11:37 am
      Permalink

      In practice it depends. There are few cases:

      – further sanitizing of file names
      – generating new file names

      For sample to try out on local box the solution works well.

    • November 14, 2019 at 1:40 am
      Permalink

      Hi,

      How to send json in the same time?
      Is there a way to be able to send for example a list of user and a list of files associated to each of them?

    • November 14, 2019 at 6:11 am
      Permalink

      Hi,

      you can create a form with file uploads and regular form fields if you need. If you have something in JSON then it can be some regular text field.

    • December 12, 2019 at 11:29 pm
      Permalink

      Dont think you should create local copies of those files if the content has to be streamed to database. Then the memory stream of the file is enough to stream that to database.

    • September 22, 2020 at 3:22 pm
      Permalink

      Hi. Can you tell me how to upload files to asp.net core from windows forms ?? Really need. But you can’t implement it

    • April 4, 2025 at 1:10 am
      Permalink

      I’m not sure why but this website is loading extremely low
      for me. Is anyone else having this problem or is it a problem on my end?

      I’ll check back later and see if the problem still exists.

    • April 8, 2025 at 1:58 am
      Permalink

      Do you have a spam problem on this site; I also am a blogger, and I was wanting to know
      your situation; we have created some nice practices and we are looking
      to exchange techniques with other folks, why not shoot me an email
      if interested.

    • April 8, 2025 at 3:07 am
      Permalink

      hello there and thank youu for your information – I have certainly
      picked up somewthing new from right here. I did however ezpertise some technical issues using
      this website, as I experienced to reload the site many times previous to
      I could get it to load correctly. I had been wondering if your hostkng is OK?
      Not that I am complaining, but slow loading instances ttimes will sometimes affect
      your placement in google and caan damage your high-quality sore if advertising
      andd marketing with Adwords. Anyway I am adding this
      RSS tto my email and cluld look out for a lot more of your respective exciting content.
      Ensure that you updage this again very soon.

    • April 9, 2025 at 8:59 am
      Permalink

      Ahaa, its nice conversation on the topic of this post att this place at this website,
      I have read all that, so now me also commenting at this place.

    • April 17, 2025 at 10:20 am
      Permalink

      Hey There. I found your blog using msn. This is a really well written article.

      I will be sure to bookmark it and come back to read more of your useful information.
      Thanks for the post. I will definitely comeback.

    • April 19, 2025 at 9:56 am
      Permalink

      Sussex Park Homes offers residentyial park homes
      fⲟr sale іn a secure riverside community. Discover affordable, brand neᴡ homes toԀay.

      Learn mоre noᴡ!

    • April 20, 2025 at 8:24 am
      Permalink

      Thanks a lⲟt for sharing this witfh all folks you reaⅼly unbderstand what yoս’respeaking
      approximately! Boοkmaгked. Please additionaⅼy seek adѵice from my site
      =). We wiill have a link traade contract among us

    • May 26, 2025 at 7:35 pm
      Permalink

      Excellent web site you have here.. It’s difficult to find high-quality writing like
      yours nowadays. I seriously appreciate individuals like you!
      Take care!!

    • June 7, 2025 at 10:12 am
      Permalink

      Hello there, just became aware of your blog
      through Google, and found that it is really informative.
      I am going to watch out for brussels. I’ll be grateful
      if you continue this in future. A lot of people
      will be benefited from your writing. Cheers!

    • June 24, 2025 at 4:17 pm
      Permalink

      Greetings! Very useful advice in this particular post!
      It’s the little changes that make the largest changes.
      Thanks a lot for sharing!

    • July 2, 2025 at 3:16 am
      Permalink

      These stories illustrate that when members leverage the expertise available at Brians club to align their entity setups with financial objectives, they unlock pathways to greater creditworthiness and business growth.

    • July 6, 2025 at 4:37 am
      Permalink

      Building credit with Brians club is a straightforward process. Start by signing up for an account on their platform. This gives you access to valuable resources and tools.

    • July 6, 2025 at 4:38 pm
      Permalink

      Establishing Brians club business credit is crucial for any entrepreneur looking to grow and secure funding. It opens doors to better financing options, ensuring that your venture can thrive.

    • July 8, 2025 at 4:02 am
      Permalink

      What’s up, its good piece of writing about media print, we all know media is a fantastic source of data.

    • July 26, 2025 at 1:16 am
      Permalink

      Hello there! I could have sworn I’ve visited this website before but after going through many of the articles I realized it’s new to me.
      Anyhow, I’m definitely pleased I found it and I’ll be bookmarking it
      and checking back often!

    • July 29, 2025 at 2:27 am
      Permalink

      Alright, champ, I recently discovered something so cool, I had to drop my sandwich and scream about it.

      This creation is a pixel miracle. It’s packed with crazy layouts, next-level thinking, and just the right amount of pixel sass.

      Sound too good? Alright, see for yourself right below!

      Need more hype? Fine. Imagine a caffeinated unicorn dreamed of a site after watching sci-fi. That’s the vibe this beast gives.

      So go ahead, and send it to your friends. Because no lie, this is pure genius.

      Boom.

    • August 6, 2025 at 5:21 am
      Permalink

      Thanks for sharing your info. I truly appreciate your efforts
      and I am waiting for your next write ups thanks once again.

    • August 17, 2025 at 5:23 am
      Permalink

      Alright, creative soul, I accidentally stumbled upon something shockingly creative, I had to shut my tabs and scream about it.

      This piece is not your usual stuff. It’s packed with smooth UX, creative magic, and just the right amount of mad energy.

      Still don’t believe me? Alright, see for yourself right this moment!

      Didn’t click? Fine. Imagine a robot designer built a site after binging inspiration. That’s the vibe this thing of wonder gives.

      So hit it, and share the love. Because real talk, this is next-level.

      You’re welcome.

    • August 18, 2025 at 9:30 pm
      Permalink

      Yo, creative soul, I accidentally found something so cool, I had to stop everything and share immediately.

      This article is a design explosion. It’s packed with color chaos, creative magic, and just the right amount of interface wizardry.

      Suspicious yet? Alright, see for yourself right below!

      Still scrolling? Fine. Imagine a robot designer dreamed of a site after binging inspiration. That’s the frequency this thing of wonder gives.

      So don’t be shy, and share the love. Because honestly, this is next-level.

      Boom.

    • August 21, 2025 at 12:29 am
      Permalink

      Yo, reader, I accidentally discovered something weirdly brilliant, I had to pause my life and tell you.

      This article is a design explosion. It’s packed with wild visuals, next-level thinking, and just the right amount of designer madness.

      Still don’t believe me? Alright, go look right here!

      You’re still here? Fine. Imagine a caffeinated unicorn coded a site after arguing with ChatGPT. That’s the energy this thing of wonder gives.

      So don’t be shy, and send it to your friends. Because honestly, this is worth it.

      You’re welcome.

    • August 29, 2025 at 12:29 am
      Permalink

      I constantly spent my half an hour to read this website’s articles everyday along with a
      cup of coffee.

    • September 1, 2025 at 7:16 pm
      Permalink

      Hi there, just became alert to your blog through Google, and found that it’s truly informative.
      I am gonna watch out for brussels. I’ll be grateful if you continue this in future.
      A lot of people will be benefited from your writing. Cheers!

      Here is my web site: aceite de jengibre

    • September 3, 2025 at 7:16 pm
      Permalink

      An interesting discussion is definitely worth comment.
      I do think that you need to write more on this topic, it may not be a taboo subject but
      usually people don’t speak about these subjects. To the next!
      Cheers!!

      my homepage web page

    • September 4, 2025 at 7:39 pm
      Permalink

      Hi there, I enjoy reading all of your article. I like to write a little comment to support you.

    • September 5, 2025 at 4:24 pm
      Permalink

      I take pleasure in, result in I found exactly what I was looking for.
      You’ve ended my four day lengthy hunt! God Bless you man. Have a nice day.
      Bye

      Feel free to visit my web page :: vetiver oil

    • September 14, 2025 at 8:26 pm
      Permalink

      What a information of un-ambiguity and preserveness of precious experience
      regarding unexpected feelings.

    Leave a Reply

    Your email address will not be published. Required fields are marked *