MVC 4文件下载

28 浏览
0 Comments

MVC 4文件下载

这是我的代码。我试着按照以下方法实现下载文件的功能,但它不能正常工作。它没有显示保存文件对话框。

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

但两种方式都没有起作用。我错过了什么吗?

admin 更改状态以发布 2023年5月21日
0
0 Comments

exe文件的正确Mimetype应为application/octet-stream而不是application/exeapplication//x-unknown - 请查看MSDN
你可以在这里查看更多定义:根据文件扩展名获取MIME类型

0
0 Comments

我不知道主要区别,但以下代码对于我来说对任何文件都运行良好...可能是因为ContentType如@Garath所建议的原因。

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

0