【问题标题】:ASP.NET MVC 4, C#: how to Download FileASP.NET MVC 4,C#:如何下载文件
【发布时间】:2014-08-06 16:38:44
【问题描述】:

我之前已经将一个文件上传到我的数据库中,现在我想从我的数据库中下载该文件。

谁能告诉我怎么做?我是 C# 和 ASP.NET MVC 的新手。

控制器:

public ActionResult Details(string id = null)
{
        Assignment assignment = db.Assignments.Find(id);

        if (assignment == null)
        {
            return HttpNotFound();
        }

        return View(assignment);
}

型号:

public string AssignmentID { get; set; }
public Nullable<System.DateTime> SubmissionDate { get; set; }
public string Status { get; set; }
[Range(0,100, ErrorMessage="Only Value between 0-100 is accepted.")]
public Nullable<decimal> Mark { get; set; }
public string Comments { get; set; }
public byte[] FileLocation { get; set; }

查看:

<div class="display-label">
    <%: Html.DisplayNameFor(model => model.FileLocation) %>
</div>
<div class="display-field">
    <%: Html.DisplayFor(model => model.FileLocation) %>
</div>

【问题讨论】:

标签: c# asp.net asp.net-mvc asp.net-mvc-4 httppostedfilebase


【解决方案1】:

由于您拥有Streambyte[] 或文件路径,您可以使用来自Controller 基类的File() 方法,并将此文件作为ActionResult 响应,例如示例:

public ActionResult Details(string id = null)
{
     Assignment assignment = db.Assignments.Find(id);

     if (assignment == null)
     {
         return HttpNotFound();
     }

     return File(assigment.FileLocation, "content/type", "fileName.extension");
}

记得获取正确的content-type 并添加带有正确扩展名的fileName

【讨论】:

    【解决方案2】:

    根据您从数据库中检索文件的方式,您可以使用 ASP.NET MVC 的 File() 辅助方法将文件返回给客户端。

    这个blog article 很好地描述了如何使用File() 帮助程序以及最终返回的内容。

    希望这会有所帮助。

    【讨论】:

    • 是的,这帮助了我们一百万 =)
    【解决方案3】:

    您必须使用@url.action 才能在视图中显示图像:

    查看:

    <%: Url.Action("ImageDetails","// your controller name//", new{ id = item.ID }) %>
    

    在你的行动中:

    public ActionResult ImageDetails(string id = null)
    {
         Assignment assignment = db.Assignments.Find(id);
    
         return File(assignment.FileLocation, "content/type", "file.extension");
    }
    

    记得获取正确的content-type 并添加正确的文件extension 否则文件将无法正确呈现在视图中。

    如果你只想下载文件不显示,那么:-

    public ActionResult Details(string id = null)
    {
         Assignment assignment = db.Assignments.Find(id);
    
         return File(assignment.FileLocation, "content/type", "file.extension");
    }
    

    【讨论】:

    • 这是什么?复制我的遮阳篷并更改它最糟糕的解决方案?无法在视图中渲染文件!
    • @FelipeOriani....试试上面的代码.. url.action 文件将在视图中呈现...
    • 如果不是图片,还会显示吗?我的意思是 Docx 或 txt
    • @WeakestInCoding...是的,可以显示任何内容,因为在控制器中返回文件时,您还指定了内容类型和文件扩展名......
    • 呃我不知道如何设置它, 我设置错了吗
    猜你喜欢
    • 2023-04-07
    • 2013-08-28
    • 2015-08-22
    • 2012-10-10
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多