c# - 从 byte[] 下载文件 C# MVC

标签 c# .net asp.net-mvc-5

我正在尝试从字节数组下载文件,但提示并未出现下载。我是否需要包含额外的 ContentDisposition 属性?如果我查看 IE 中的网络流量,我可以看到文件请求有效并且返回 200,此外我还可以从 IE 调试工具内容下载文件。

字节数组中存储的文件是Word文档。我已将 mime 类型设置为:

应用程序/vnd.openxmlformats-officedocument.wordprocessingml.document

文档文件名为:QuickStartGuide.docx

下载提示未出现的原因?

[HttpPost]
[ValidateAntiForgeryToken]
public FileContentResult DocumentDownload(int documentId)
{
    try
    {
        var document = BusinessLayer.GetDocumentsByDocument(documentId, AuthenticationHandler.HostProtocol).FirstOrDefault();

        System.Net.Mime.ContentDisposition contentDisposition = new System.Net.Mime.ContentDisposition();

        contentDisposition.FileName = document.FileName;
        contentDisposition.Inline = false;

        var result = new FileContentResultWithContentDisposition(document.FileBytes, document.FileType, contentDisposition);

        return result;
    }
    catch
    {
        throw;
    }
}


public class FileContentResultWithContentDisposition : FileContentResult
{
    private const string ContentDispositionHeaderName = "Content-Disposition";

    public FileContentResultWithContentDisposition(byte[] fileContents, string contentType, ContentDisposition contentDisposition)
        : base(fileContents, contentType)
    {
        // check for null or invalid ctor arguments
        ContentDisposition = contentDisposition;
    }

    public ContentDisposition ContentDisposition { get; private set; }

    public override void ExecuteResult(ControllerContext context)
    {
        // check for null or invalid method argument
        ContentDisposition.FileName = ContentDisposition.FileName ?? FileDownloadName;
        var response = context.HttpContext.Response;
        response.ContentType = ContentType;
        response.AddHeader(ContentDispositionHeaderName, ContentDisposition.ToString());
        WriteFile(response);
    }
}

最佳答案

你的action方法修饰为POST,但是文件下载有一个GET操作,下载也不需要防伪验证。

ASP.NET MVC 框架已经内置了FileResult。 MVC Controller 本身具有便利函数 File(...) ( https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.file(v=vs.118).aspx )

为了向浏览器发出下载文件的信号,您必须指定内容类型和下载文件名。这会将您的代码缩短为:

[HttpGet]
public FileResult DocumentDownload(int documentId)
{
    var document = BusinessLayer.GetDocumentsByDocument(documentId, AuthenticationHandler.HostProtocol).FirstOrDefault();

    return File(document.FileBytes, document.FileType, document.FileName);           
}

关于c# - 从 byte[] 下载文件 C# MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39047713/

相关文章:

c# - 从选择中排除 DataGridView 的最后一列

.net - 如何指示 NDepend 忽略 EF 类?

JavaScript 桌面应用程序?

c# - 如何在已编译的 .NET 程序集中使用 Matlab 对象?

c# - 如何使用 structuremap asp.net mvc 注册可选装饰器或带有可选参数的装饰器?

c# - 在使用 MasterPage 的网络表单上使用 CSS

c# - Web 应用程序中基于文化的 ToString() 方法

css - 向 ASP.Net MVC 5 添加新主题不起作用

c# - asp .net MVC 5 中的异步任务

asp.net-mvc-routing - 无法解析到 MVC Controller 的属性路由