HOW TO UPLOAD IMAGE IN MVC?

Total Post:3

Points:21
C#  Mvc 
C#
 595  View(s)
Ratings:
Rate this:
Hello, 
I am having problem in uploading an image through MVC in C#.
Anyone please help me with step by step Procedure to upload  image using Entity Framework.
  1. Post:52

    Points:366
    Re: HOW TO UPLOAD IMAGE IN MVC?

     You can use the same code as described below

    Your view code 

    @{
        Layout = null;
    }
     
    <!DOCTYPE html>
     
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Upload</title>
    </head>
    <body>
        <div>
            @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <label for="file">Upload Image:</label>
        <input type="file" name="file" id="file" style="width: 100%;" />
        <input type="submit" value="Upload" class="submit" />
    }
        </div>
    </body>
    </html>
     


    your controller should have action method which would accept HttpPostedFileBase


      public ActionResult FileUpload(HttpPostedFileBase file)
            {
                if (file != null)
                {
                    string pic = System.IO.Path.GetFileName(file.FileName);
                    string path = System.IO.Path.Combine(
                                           Server.MapPath("~/images/profile"), pic);
                    // file is uploaded
                    file.SaveAs(path);
     
                    // save the image path path to the database or you can send image
                    // directly to database
                    // in-case if you want to store byte[] ie. for DB
                    using (MemoryStream ms = new MemoryStream())
                    {                    file.InputStream.CopyTo(ms);
                        byte[] array =ms.GetBuffer();
                    }
     
                }
                // after successfully uploading redirect the user
                return RedirectToAction("actionname", "controller name");
            }
     

     

      Modified On Apr-11-2018 10:44:09 PM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!