【问题标题】:My MVC View displays file content into the view instead of downloading as a file我的 MVC 视图将文件内容显示到视图中,而不是作为文件下载
【发布时间】:2017-02-21 18:26:06
【问题描述】:

我找到了这个链接。 ASP.NET MVC download image rather than display in browser

我尝试了所有方法,我的操作方法将文件转储到视图中,而不是下载。我希望能够单独下载该文件。谢谢

        if (extension.ToLower() == ".docx")
        { // Handle *.jpg and   
            contentType = "application/docx";
        }
        else if (extension.ToLower() == ".jpg")
        {// Handle *.gif   
            contentType = "image/jpeg jpeg jpg jpe";
        }
        else if (extension.ToLower() == ".pdf")
        {// Handle *.pdf   
            contentType = "application/pdf";
        }
        Response.ContentType = contentType; // "application/force-download";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
        Response.WriteFile(FilePath );
        Response.Flush();
        Response.End();[![View after clicking download button][1]][1]

【问题讨论】:

  • 尝试使用application/octet-stream mime 类型,看看浏览器是否为您提供了保存而不是显示的选项
  • 我做到了。它仍然表现相同。
  • 响应头是什么样的?

标签: asp.net-mvc


【解决方案1】:

您的问题可能与以下类似:

How can I present a file for download from an MVC controller?

Returning a file to View/Download in ASP.NET MVC

您可以使用以下代码从操作方法中返回FileResultFileStreamResult,而不是使用Response.WriteFile

    if (extension.ToLower() == ".docx")
    { // Handle *.jpg and   
        contentType = "application/docx";
    }
    else if (extension.ToLower() == ".jpg")
    {// Handle *.gif   
        contentType = "image/jpeg jpeg jpg jpe";
    }
    else if (extension.ToLower() == ".pdf")
    {// Handle *.pdf   
        contentType = "application/pdf";
    }
    Response.ContentType = contentType; // "application/force-download";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);

    // returning the file for download as FileResult
    // third input parameter is optional
    return File(FileName, contentType, Server.UrlEncode(Filename));

NB:正如 Leo 在https://stackoverflow.com/a/36776089/6378815 中所说,如果响应头已经包含Content-Disposition 部分,Response.AppendHeader 方法可能会导致浏览器无法呈现文件内容。您可能想尝试这种方式:

Response.Headers.Add("Content-Disposition", "attachment; filename=" + FileName);

补充参考:

Response.WriteFile() -- not working asp net mvc 4.5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 2011-06-29
    • 1970-01-01
    相关资源
    最近更新 更多