Click here to Skip to main content
14,217,056 members
Rate this:
Please Sign up or sign in to vote.
See more:
Dear all,
I want to upload an image by using asp.net mvc 3. I use razor(cshtml).I have failed to finish this work.
I am able to upload image by asp.net webform. but need to do using mvc.

Please help full process to me soon.

Thanks,
Emon Mahmud
Posted
Updated 23-Jun-16 0:26am
Rate this:
Please Sign up or sign in to vote.

Solution 1

Dear Mahmud,

You can use HttpPostedFileBase.InputStream.Read() method read the upload stream to a buffer, and then save it to the database field. For example:

[HttpPost]
        public ActionResult Create(string fileTitle)
        {
            try
            {
                HttpPostedFileBase file = Request.Files[0];
                byte[] imageSize = new byte[file.ContentLength];
                file.InputStream.Read(imageSize, 0, (int)file.ContentLength);
                Image image = new Image()
                {
                    Name = file.FileName.Split('\\').Last(),
                    Size = file.ContentLength,
                    Title = fileTitle,
                    ID = 1,
                    Image1 = imageSize
                };
                db.Images.AddObject(image);
                db.SaveChanges();
                return RedirectToAction("Detail");
            }
            catch(Exception e)
            {
                ModelState.AddModelError("uploadError", e);
            }
            return View();
        }


View

  @using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <fieldset>
        <legend>Upload Image</legend>

        @Html.Label("Title")
        @Html.Editor("fileTitle")<br />
        Upload File: <input type="file" name="test" />
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}


I think this will helpful to you

Thanks
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

   
Comments
CHill60 29-Jul-15 9:30am
   
Post is over 3 years old and has an accepted solution. The link is broken.

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100