c# - ASP.NET MVC 4,C# : how to Download File

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

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

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

Controller :

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>

最佳答案

因为你有一个 Streambyte[] 或一个文件的路径,你可以使用 File() 方法来自 Controller 基类,并将此文件响应为 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

关于c# - ASP.NET MVC 4,C# : how to Download File,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25165649/

相关文章:

c# - 使用 system.management 关闭时访问被拒绝

c# - 通过 SOAP 网络服务传输二进制数据?

c# - SQL Server返回给C#的是什么

c# - 在运行时从自定义 UITypeEditor 中的属性上插入自定义 TypeConverter

asp.net - 如何在回发时更改复合服务器控件中的子控件

mysql - 如何连接MVC和MYSQL

c# - 查看渲染额外的小数位

c# - Entity Framework 添加或更新

jquery - 从 ASP.NET MVC 操作返回部分 View 和 JSON

c# - 如何在 Asp.Net MVC 4 中模拟 HttpContext.User.Identity.Name