Skip to main content
 首页 » 编程设计

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

2024年02月05日12zlslch

我正在尝试从字节数组下载文件,但提示并未出现下载。我是否需要包含额外的 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);            
}