Click here to Skip to main content
15,895,777 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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 3-Mar-21 7:48am

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
 
Share this answer
 
 
Share this answer
 
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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900