如何从数据库下载文件,并在Asp.net核心MVC中将其作为图像获取?

问题描述

我一直在阅读和解决文件上传上传数据库的问题!我刚刚完成上传工作,所以现在我将文件保存在数据库的Binary中!我也在视图中显示名称

@model IEnumerable<RH_Files>

<div class="tableContainer">
    <table class="table table-striped">
        <thead>
            <tr>
                <th>
                    @Html.displayNameFor(p => p.Name)
                </th>
            </tr>
        </thead>
        <tbody >
            @foreach (var item in Model)
            {
              <tr>
                  <td>
                      @Html.displayFor(model => item.Name)
                  </td>
              </tr>
            }
        </tbody>
    </table>
</div>

如您所见:

enter image description here

我的模特:

 public class RH_Files
    {
        [Key]
        public int id { get; set; }
        public string Name { get; set; }
        public string ContentType { get; set; }
        public Byte[] Data { get; set; }
    }

现在我需要的是为每个项目都有一个下载按钮,这将触发一个c#操作,该操作将下载选定的文件...

感谢您的帮助!

解决方法

在您的控制器中:

public FileResult Download(int id)
{
      var fileToRetrieve = db.GetFile(id);
      return File(fileToRetrieve.Data,fileToRetrieve.ContentType);
}