当我强制从页面下载文件时,它会通过空格/C#拆分文件名



这是我的强制下载代码:

        // URL = Download.aspx?Url=How to use the Application.txt    
        string q = Request.QueryString["Url"].ToString();
        Response.Clear();
        Response.AddHeader("Content-disposition", "Attachment; Filename=" + file);
        Response.ContentType = "Text/Plain";
        Response.WriteFile(Server.MapPath("Directory/" + q));
        Response.End();

在Firefox中出现的对话框显示:您将打开文件:文件名显示只是屁股如何(名称应该是:如何使用应用程序.txt)。如果我试图为自己命名文件名,我提到的 sama:

Response.AddHeader("Content-disposition", "Attachment; Filename=How to use the Application.txt");

同样的阿皮尔斯。请帮忙!

Mime 文件名应用双引号引起来。

Response.AddHeader("Content-disposition", 
                   "Attachment; Filename="" + file + """);
    

这可以在RFC 2616(HTTP 1.1)中找到。

Content-Disposition: attachment; filename="fname.ext"

在 RFC 6266 中进行了修订,如果文件名不包含空格等不允许的字符,则也允许不带引号的文件名。

内容处置:附件;文件名=示例.html

您应该在

文件名两边加上双引号。具体操作方法如下:

    string q = Request.QueryString["Url"].ToString();
    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=""
        + file + """);
    Response.ContentType = "text/plain";
    Response.WriteFile(Server.MapPath(d + q));
    Response.End();

请注意,我还将您的字符串大写/小写更改为现在的"内容处置","附件","文件名","文本/纯文本"。您应该以这种方式使用它们,以免遇到处理非常严格的浏览器的麻烦。

如果这不能正常工作,请尝试:

    Response.AddHeader("Content-Disposition", "Attachment;
        Filename="" + HttpUtility.UrlEncode(file) + """);

然后对文件名中的空格进行 URL 编码。

最新更新