Upload a file/image with form data in MVC

Nowadays I am starting out in ASP.NET MVC, one of the things I struggled with the most was how to upload a file/image with form data in MVC. I googled numerous tutorials and guides that showed me how to do file uploads in ASP.NET MVC, but they all had the POST action only receiving the upload itself, not a form full of data and a file upload. Hopefully, this article will save the times and efforts of newbies.

Simply I am creating a view with a textbox “name” and a input file tag with a form in which we need to set enctype as “multipart/form-data” as below given

Here we are calling HomeController addImage action on form submit so let’s view the HomeController :

Here in this addImage action, We are taking FormCollection as a parameter by which we can access the form data like name. Here we are using Request object for getting the files which is assigned to a variable “postedFile” which is of HttpPostedFileWrapper. By using this, we can access each and every property of a file object and can implement the conditions and using SaveAs method we can save the file at specified location.

So Uploading a file/image with form data in MVC, is a easy process like ASP.NET but only need to get the guide to do that.

If you find any query regarding uploading a file/image in MVC, feel free to write us so that we can reach to you by providing solution.

Like this Post? Share