MVC 4文件下载

本文关键字:文件下载 MVC | 更新日期: 2023-09-27 18:29:00

以下是我的代码,我尝试了以下方法来放置下载文件的功能,但它不能正常工作。它不显示"保存文件"对话框。

 protected virtual FileResult Download(string FileName, string FilePath)
 {
        Response.AppendHeader("Content-Length", FileName.Length.ToString());
        return File(FilePath, "application/exe", FileName);
 }

也尝试过这种方式:

protected virtual ActionResult Download(string FileName, string FilePath)
{
    Response.Clear();
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
    Response.AppendHeader("Content-Length", FileName.Length.ToString());
    Response.ContentType = "application//x-unknown";
    Response.WriteFile(FilePath.Replace("''", "/"));
     Response.Flush();
    Response.End(); 
}

但两者都不起作用。我错过了什么?

MVC 4文件下载

我不知道主要区别,但下面的代码对我来说适用于任何文件。。可能是因为@Garath建议的ContentType。

var fileInfo = new System.IO.FileInfo(oFullPath);
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", String.Format("attachment;filename='"{0}'"", yourfilename));
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.WriteFile(oFullPath);
            Response.End();

exe文件的正确最小值是application/octet-stream,而不是application/exeapplication//x-unknown-请查看MSDN您可以在这里查找更多定义:从文件扩展名获取MIME类型