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
1 2 3 4 5 6 7 8 9 10 11 | <form name="form1" method="post" action="Home/addImage" enctype="multipart/form-data"> <div> Name: @Html.TextBox("name") <label> Browse File</label> <input name="myFile" type="file" /> </div> <div> <input type="submit" value="Upload" /> </div> </form> |
Here we are calling HomeController addImage action on form submit so let’s view the HomeController :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | [HttpPost] public void addImage(FormCollection form) { string name = form["name"]; if (Request.Files.Count > 0) { var docFiles = new List<string>(); foreach (string file in Request.Files) { var postedFile = Request.Files[file]; var filePath = Server.MapPath("~/images/" + postedFile.FileName); postedFile.SaveAs(filePath); docFiles.Add(filePath); } } else { // else code whatever you want } return ; } |
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.
支持,只有支持才是访问博客的正确方式!
很荣幸来访您的博客,留言只是证明我来过!
对你爱爱爱不完,我可以天天月月年年看你博客到永远!
从百度进来的,博客不错哦!
学习使人进步,到此拜读!
富强、民主、文明、和谐,自由、平等、公正、法治, 爱国、敬业、诚信、友善。
感觉不错哦,认真拜读咯!
真是时光荏苒!
从百度进来的,拜读一下贵站博文先
丁酉年(鸡)二月十五 2017-3-12
就是喜欢看你博客!
拜读大侠博客,感悟人生道理!
研究研究,学习学习。
不错,不错,看看了!