【问题标题】:MVC 4 File DownloadMVC 4 文件下载
【发布时间】:2013-08-28 23:29:27
【问题描述】:

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

 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(); 
}

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

【问题讨论】:

  • 我希望您了解文件路径和文件名变量伴随的安全问题...
  • 文件名长度!= 内容长度。此外,它可能的浏览器正在阻止可执行文件下载。我知道我的 IE 确实如此...... Chrome 会抛出一个“你绝对确定吗?”提示。
  • 看到这个类似的问题:stackoverflow.com/questions/3604562/…
  • 我也尝试使用 .doc 文件,并且在同一位置它适用于 asp.net 中的 exe 文件。
  • 这可能是因为文件压缩(我相信默认)。文本有效,因为浏览器知道如何解压缩文件。压缩后的二进制文件(PDF、DOCX 等)看起来仍然像二进制文件。

标签: c# asp.net-mvc-4 download mime-types


【解决方案1】:

我不知道主要区别,但是对于任何文件,以下代码对我来说都可以正常工作。可能是因为 @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();

【讨论】:

    【解决方案2】:

    exe 文件的正确 mimitype 是 application/octet-stream 而不是 application/exeapplication//x-unknown - check MSDN 您可以在这里查看更多定义:Get MIME type from filename extension

    【讨论】:

    • 我一切正常,但问题是只下载了 txt 文件,但下载了 doc 文件或 pdf 文件但格式已损坏。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2013-05-01
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多