Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi, I am doing a project where I have to save image in database and then show/retrieve them in main page. I can save image in a folder but doesn't retrieve them. Can anyone give me a proper solution for it..

My Model Class is likes
public class Product
 {
     [Key]
     public int ProductId { set; get; }

     public IEnumerable<HttpPostedFileBase> Images { get; set; }
 }

My Controller is likes
C#
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Product product)
{
    if (ModelState.IsValid)
    {
        db.Entry(product).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }

     return View(product);
}

My View is likes
C#
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Product</legend>
        <div class="editor-field">
            <h3>Image:</h3>
            <input type="file" name="Image" id="Images" multiple />
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
Posted
Comments
Prasad Avunoori 6-May-14 1:18am    
What's your problem?
mgsdew 6-May-14 7:47am    
Are you see my post properly ??

1. First solution is that you should save the images in the SQL database into "Image" fields, so in this way the image will be saved as array of bytes.

2.Second solution is to have into your web application a Doc folder used for storing the files, and in this case you must give access/permission to this folder into the web.config.

You can see both solutions implemented into my next article (with ASP.NET MVC4.0 source code provided): MVC Basic Site: Step 3 – Dynamic Layouts and Site Admin with: AJAX, jqGrid, Controller Extensions, HTML Helpers, and more[^]. See details especially in ImageResult class and also in OpenFileResult class and their usage in the application.
 
Share this answer
 
v2
Comments
mgsdew 6-May-14 7:45am    
I just see your project. But, I don't understand it clearly.. I also can't download your source code :(
Raul Iloc 6-May-14 7:50am    
You should login by using your CodeProject account and the download will work.
you can stored whole path in DB in which the images stored in folder. and then retrived and assign the path image.source= path.
 
Share this answer
 
Comments
mgsdew 6-May-14 7:44am    
I also want to do that. But I don't know this process. Can u give me a proper solution after seeing my given document ?
 
Share this answer
 
Comments
mgsdew 6-May-14 7:41am    
I already seen this but there are no 'View' model in there. So,it's still unclear for me..:(
Sanket Saxena 6-May-14 7:46am    
your problem is in saving or retriving? and what is the error you get?
mgsdew 6-May-14 7:51am    
I can save 'file/image' in Content/images folder by my given documentation way. Now I want to retrieve them from target place by using 'Id'. So, now my problem is in retrieve data..
Hey, I just solve my problems by using some different method

This is my model class named 'Picture'
C#
   public class Picture
    {
        public int PictureId { get; set; }
        public IEnumerable<httppostedfile> Image { get; set; }
        public string Name { get; set; }
        public long Size { get; set; }
        public string Path { get; set; }
    }
</httppostedfile>


Then I create a controller named 'PictureController' and write 2 method inside there. I also create a folder named 'UplodedFiles' in project directory to save upload images in that folder.
C#
      [HttpPost]
       public void Upload()
       {
           foreach (string file in Request.Files)
           {
               var postedFile = Request.Files[file];
               postedFile.SaveAs(Server.MapPath("~/UploadedFiles/") + Path.GetFileName(postedFile.FileName));
           }
       }
         public ActionResult List()
	        {
	            var uploadedFiles = new List<picture>();
	 
	            var files = Directory.GetFiles(Server.MapPath("~/UploadedFiles"));
	 
	            foreach(var file in files)
	            {
	                var fileInfo = new FileInfo(file);

                    var picture = new Picture() { Name = Path.GetFileName(file) };
	                picture.Size = fileInfo.Length;
	 
	                picture.Path = ("~/UploadedFiles/") + Path.GetFileName(file);
	                uploadedFiles.Add(picture);
	            }
	 
	            return View(uploadedFiles);
	        }
</picture>


Than create a 'Index' view to upload files
C#
@model FileUploadAndRetrive.Models.Picture

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm("Upload", "Picture", FormMethod.Post, new { enctype="multipart/form-data" }))
{ 
    <div>
        Select a file: <input type="file" name="fileUpload" />

        <input type="submit" value="Upload" />
    </div>
 }


Finally I create another view named 'List' for showing uploaded images

C#
@model IEnumerable<fileuploadandretrive.models.picture>

@{
    ViewBag.Title = "List";
}

<h2>List</h2>

<table>
    <tr>
        <td> Name </td>
        <td> Size </td>
        <td> Preview </td>
    </tr>
    @foreach (var file in Model)
    {
        <tr>
            <td> @file.Name </td>
            <td> @file.Size </td>
            <td>
                <img src="@Url.Content(file.Path)" />
            </td>
            
        </tr>
    }
</table>
</fileuploadandretrive.models.picture>
 
Share this answer
 

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