Upload files in ASP.NET MVC with JavaScript and C#.

In an earlier [post](GHOST_URL/upload-files-to-the-server-using-javascript-and-mvc-webapi/" target="_blank), I described how to implement a file upload using [Ajax](http://api.jquery.com/jquery.ajax/" target="_blank) and [ASP.NET WebAPI](http://www.asp.net/web-api" target="_blank). This works great but it means that you need to have a WebAPI controller to manage the requests. If you already have a WebAPI in your solution then you can simply extend it to manage file uploads. However, there's no reason to add a WebAPI only for file uploads. Instead you can use an MVC controller to perform the same task.

The goal is to upload a file to the server using just JavaScript and an MVC controller without submitting a form. Most of the examples I found out there require a form submission. But there are a lot of situations where a form submission may not be desirable. The code example below takes advantage of jQuery and Ajax on the client side to post a file to an ASP.NET MVC controller and save the file on disk.

NOTE - make sure you check that your browser supports window.formdata before implementing this solution. You can find information about the supported browsers here: http://caniuse.com/#search=formdata

HTML/Javascript code

First we need to add an <input type=file... element on the page to allow users to browse and upload files.

    <input type="file" name="UploadFile" id="txtUploadFile" class="makethispretty"  />

Now, lets add the javascript code to glue everything together:

This method works by attaching an event listener to the textbox input element using jQuery and 'fire' on change, i.e when the user browses and selects a file(s). We then create a new FormData object where we load all the file data.

The last step is to perform the ajax call which posts the data to the MVC contoller and logs the success to the console.

MVC Controller

The MVC controller method is outlined below:

The method accepts an id parameter (of type string) and reads the file data from the Request. To persist the file to disk, we get the filename and then use a FileStream to write the data to the destination path.

Bonus: the method can process multiple files within a single request, so you can change your input element to enable multiple file upload like this:

<input type="file" name="File Upload" id="txtUploadFile" multiple>

It is important to note that there are many different ways to upload files to the server in MVC ASP.NET, so you should choose the one that better matches your requirements. You can find implementation to two ways below:

  • [file upload with WebAPI](GHOST_URL/upload-files-to-the-server-using-javascript-and-mvc-webapi/" target="_blank)
  • [file upload with MVC](GHOST_URL/upload-files-in-asp-net-mvc-with-javascript-and-c/" target="_blank)

The choice is yours...

  • Share this post on