In an earlier post, I described how to implement a file upload using Ajax and ASP.NET WebAPI. 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.
NOTE - make sure you check that your browser supports
window.formdatabefore implementing this solution. You can find information about the supported browsers here: http://caniuse.com/#search=formdata
First we need to add an
<input type=file... element on the page to allow users to browse and upload files.
<div> <input type="file" name="UploadFile" id="txtUploadFile" class="makethispretty" /> </div>
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.
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
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:
The choice is yours...