0

I am trying to save uploaded image in database and show in view using .Net MVC but no success.

Here is my code.

Model:

    public class TeamStartup
    {

        public string thumb { get; set; }

    }

Controller:

    public class CityDetailController : Controller
    {

//Save Team Member StartUp  Picture
        private string SaveTeamMemberPicture(HttpPostedFileBase thumb)

        {
            string fileName = default(string);
            string savedPath = default(string);
            string[] validExtensions = new string[4] { ".png", ".jpg", ".gif", ".jpeg" };

            if (thumb != null && thumb.ContentLength > 0)
            {

                fileName = Path.GetFileName(thumb.FileName);
                var fileExt = new FileInfo(fileName).Extension;

                if (!validExtensions.Contains(fileExt.ToLower()))
                {
                    ModelState.AddModelError(string.Empty, "Image type Invalid");
                }
                if (thumb.ContentLength > 1048576)
                {
                    ModelState.AddModelError(string.Empty, "file size limit exceeds (Max 1MB)");
                }

                if (ModelState.IsValid)
                {

                    fileName = DateTime.Now.Ticks.ToString();
                    var path = Path.Combine(Server.MapPath(@System.Configuration.ConfigurationManager.AppSettings["UploadsPath"] + "/Avatars/City"), fileName);

                    thumb.SaveAs(path);
                    savedPath = fileName;
                }
            }
            return savedPath;
        }
}

It doesn't save and show anything in database, Any help would be appreciated.

Thank You.

  • Does this answer your question? [Uploading/Displaying Images in MVC 4](https://stackoverflow.com/questions/16255882/uploading-displaying-images-in-mvc-4) – Hamed Moghadasi Jan 28 '20 at 11:59

2 Answers2

0

HttpPostedFileBase provides InputStream property. Use it to get the actual binary version of the image. Usually it is Base64 encoded version of the image. Save this in the database.

using(StreamReader sr = new StreamReader(thumb.InputStream)) 
{
  let image = sr.ReadToEnd();

  //save this string 'image' in DB
}

To display it, return the Base64 string (saved in DB) to response in image tag by setting its src attribute to data:image/png;base64, <Base64String>. Check below example.

<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
    AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
        9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
Aditya Bhave
  • 998
  • 1
  • 5
  • 10
0

change your model:

  public string ImageName{ get; set; }

change your view:

 @using (Html.BeginForm("Create", "Posts", FormMethod.Post, new { enctype = "multipart/form-data" }))

 <input type="file" name="ImgUp" id="ImgUp"  accept="image/*"/>

And Your Controller:

 public ActionResult Create(HttpPostedFileBase ImgUp)
    {
        if (ModelState.IsValid)
        {

            if (ImgUp != null)
            {
                post.ImageName = Guid.NewGuid() + Path.GetExtension(ImgUp.FileName);
                ImgUp.SaveAs(Server.MapPath("/Images/" + post.ImageName));

            }

            _dbContext.InsertPost(post);
            return RedirectToAction("Index");

        }

    }

Your Image save In Your Root Project In Images Folder And For Display Image:

 <img class="imgindex" src="/Images/@Model.ImageName" />
Morteza Ttt
  • 1
  • 1
  • 3