【问题标题】:Upload,Save and Retrieve Image from database by using their Id in Code First Method使用代码优先方法中的 ID 从数据库上传、保存和检索图像
【发布时间】:2014-06-24 10:04:04
【问题描述】:

从过去的 10 天开始,我正在尝试网络中提供的许多方法/示例/教程来解决我的问题。但是,对于所有这些情况,我都失败了。 我想上传特定/多个产品的图片,将它们保存在数据库中,并通过调用它们的 ID 将它们显示在主页中。谁能给我一步一步的例子/教程/链接。 请不要给出部分答案/建议。因为我已经对这些感到厌烦了。

【问题讨论】:

  • 在谷歌上搜索本书Pro ASP.NET MVC 4。里面有一个很好的例子。你可以拥有一个。在 Google 图书上查看
  • @lnanikian 我已经开始阅读那本书,但不了解他们的数据库保存方法..
  • 你能展示你尝试了什么吗?所以从那里我们可以帮助你

标签: c# asp.net asp.net-mvc-4 entity-framework-4


【解决方案1】:

我刚刚解决了我的问题,这里是解决方案:

这是我的模型类

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

这是我的控制器

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

这是我的“索引”视图

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

通过这个“列表”视图,我显示图像列表:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 2014-01-29
    • 2012-02-26
    • 1970-01-01
    相关资源
    最近更新 更多