Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Upload File in ASP.NET MVC

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 303
    Comment on it

    "File Upload in ASP.NET MVC"

        File upload is one of the common feature that is required in almost every application. In this article we will discuss how to use this upload file functionality in Asp .Net MVC.

    Step 1: In the Controller say HomeController write an action method:

    public ActionResult FileUpload()
            {
                return View();
            }
    

    Step 2: Create a view for this action method (i.e .cshtml file), In the View write the following code:

    @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <div>
            <b><u>File Upload in MVC3 By Using Razor</u></b>
            Select Image
            <input type="file" name="file" />
            <input type="submit" value="Upload Image" name="Command" /><br />
        </div>
    
    }
    

    In the above code look at the following attribute inside the Form tag:

     new { enctype = "multipart/form-data" }
    

    This is the attribute that will help to find the uploaded file at the Controller end.

    Step 3: Now in the HomeController create a post method by adding the [HttpPost] attribute, for FileUpload() ActionMethod .

    [HttpPost]
    public ActionResult FileUpload(HttpPostedFileBase file)
    {
        return View();
    }
    

    Step 4: Now as you have got the uploaded file, you can save it to any location example:

    [HttpPost]
    public ActionResult FileUpload(HttpPostedFileBase file)
    {
      /*Geting the file name*/
      string filename = System.IO.Path.GetFileName(file.FileName)                         
      /*Saving the file in server folder*/
      file.SaveAs(Server.MapPath("~/Images/" + filename));
      string filepathtosave = "Images/" + filename;           
      return View();
    }
    

    Hope it helps you......Happy Coding!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: