Uploading a file in ASP.NET Core 2.0

As part of the web app I’m currently developing using ASP.NET Core 2.0, I needed to allow the user to upload files to the server. The file upload control I am using is the Kendo UI Upload control, but the underlying process will be similar irrespective of the underlying UI control that you are using.

To achieve this I am using an ASP.NET Core page handler. Within this page handler I have placed the Kendo UI Upload control. The page handler contains the name of the page handler and the HTTP method to use.

The below code is the Razor (.cshtml) syntax (simplified) that demonstrates how I have created the page handler and the Kendo UI Upload control.

Hide Copy Code

<form asp-page-handler="upload" method="post">

In the example above it should be noted that the name of the page handler is “upload” and the HTTP method will be a POST. Without going into a full description of ASP.NET Core page handlers, the name of the form page handler and the HTTP method dictate the name of the page handler on the Razor code-behind.

When the user clicks the Save button the files that have been specified for upload will be posted to the ASP.NET Core “upload” page handler.

Hide Copy Code

public void OnPostUpload(IEnumerable<IFormFile> files)
//do something with the file(s) here

Note: the name of the Kendo UI Upload control MUST be the same as the name of the parameter received by the page handler i.e. “files” in this example. The files get posted to the page handler when the form is submitted. You can then process the files in any way you want. Note also that the type of parameter is different to previous versions of ASP.NET which used HttpPostedFileBase. With ASP.NET Core the posted files are of type IEnumerable<iformfile>.

ASP.NET Core makes handling file uploads very simple and straight forward. Doing so is even easier using the Kendo UI Uploadcontrol which reduced the amount of code I had to write. Files can be uploaded asynchronously and in multiples too.

A father, cyclist, vegetarian, atheist, geek and multiple award winning technical author. Loves real ale, fine wine and good music. All round decent chap.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store