c# - 使用 Code First 方法中的 Id 从数据库上传、保存和检索图像

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

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

最佳答案

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

这是我的模型类

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

这是我的 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);
        }

这是我的“索引” 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> }

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

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

关于c# - 使用 Code First 方法中的 Id 从数据库上传、保存和检索图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23517615/

相关文章:

c# - 从自定义控件继承

c# - 如何更改 Infragistics 的 UltraGrid 过滤器行的背景颜色?

asp.net - 取消跨页回发?

c# - 从 ASP.NET MVC 创建打开的 XML Excel 工作表时出错

c# - 对于没有默认无参数构造函数的数据类型,Web API 静默失败

c# - 从哪里开始 QuickBooks 开发?

c# - 将 WPF 项目链接到 Windows Azure 数据库

c# - 不使用 Visual Studio 运行 ASP/C#

c# - 生成后事件不适用于 msbuild.exe

.net - MVC4 风格捆绑给出 403