Search code examples
c#asp.netasp.net-mvc-4entity-framework-4

Upload,Save and Retrieve Image from database by using their Id in Code First Method


from last 10 days I am trying many ways/example/tutorials which are provide in net to solve my problems. But, for all of those cases I fail down. I want to upload images for specific/multiple products, save them in database and display them in Home page by calling their ID. Can anyone give me step by step example/tutorials/link for this. Please don't give an partial answer/suggestion. Because I am already bore about those.


Solution

  • I just solved my Problems and here is the solution :

    This is my Model Class

    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; }
    }
    

    This is my Controller

       [HttpPost]
       public void Upload()  //Here just store 'Image' in a folder in Project Directory 
                             //  name 'UplodedFiles'
       {
           foreach (string file in Request.Files)
           {
               var postedFile = Request.Files[file];
               postedFile.SaveAs(Server.MapPath("~/UploadedFiles/") + Path.GetFileName(postedFile.FileName));
           }
       }
         public ActionResult List() //I retrive Images List by using this Controller
            {
                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);
            }
    

    This is my 'Index' View

        @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> }
    

    By this 'List' view I show the Image List:

    <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>
    }