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

只谈情不闲聊 提交于 2019-12-18 12:08:58

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/23517615/upload-save-and-retrieve-image-from-database-by-using-their-id-in-code-first-met

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!