Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi friends, I want to upload image in folder in my MVC2 project. I have the following code :

Controller Code :

C#
public ActionResult UploadFile()
        {
            return View();
        }
        
        [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase file)
        {            
            if (file.ContentLength > 0)
            {
                try
                {
                    var filename = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("../images/"), filename);
                    file.SaveAs(path);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return RedirectToAction("Login");
        }


View Code :

ASP.NET
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>UploadFile</title>
</head>
<body>
    <div>
    <% using (Html.BeginForm("UploadFile", "Account", FormMethod.Post, new {enctype = "multipart/form-data" }))
       {%>
       <div><input type="file" id="file" name="file" /></div>
       <div> <input type="submit" value="Upload" /></div>          
          <%} %>
    
    </div>
</body>
</html>


my image is coming in HttpPostedFileBase file but not saved in folder, I am so confused where I am wrong because my image is coming in file and my path is also correct.

Please help me thanks in advance.

Parveen Rathi
Posted

1 solution

Hello
This code is correct.

The problem is with this part.

<% using (Html.BeginForm("UploadFile", "Account", FormMethod.Post, new {enctype = "multipart/form-data" }))


What is the name of your main controller? account ?
view name = uploadfile
actioncontroller =UploadFile

public class AccountController : Controller
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900