【问题标题】:How to download files from a database, and get them as image in Asp.net core MVC?如何从数据库下载文件,并将它们作为图像在 Asp.net 核心 MVC 中获取?
【发布时间】:2022-02-27 12:56:51
【问题描述】:

我一直在阅读和解决下载和上传文件到数据库的问题!我刚刚完成了上传工作,所以现在我将我的文件以二进制形式保存在数据库中!我也在视图中显示名称:

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

如您所见:

我的模特:

 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# 操作...

感谢任何帮助!

【问题讨论】:

  • 在您的控制器中创建一个返回 File(...) 的操作
  • 这是一个link,关于从数据库中检索文件。

标签: c# asp.net-mvc asp.net-core


【解决方案1】:

在您的控制器中:

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

【讨论】:

  • 我要改变那个分贝吗?对于 _context.RH_Files ?如果是这样,它给了我一个错误,它说它不包含 GetFile 的定义。
  • 这只是一个例子。你需要从数据库中获取文件
  • 如果你想查看文件创建另一个方法但返回内容而不是文件
猜你喜欢
  • 2011-05-07
  • 2016-10-23
  • 2021-11-28
  • 1970-01-01
  • 2020-08-22
  • 2017-04-26
  • 2020-07-31
  • 1970-01-01
  • 2021-10-02
相关资源
最近更新 更多