When I force downloading a file from a page, it split te file name by SPACE /C#?

只谈情不闲聊 提交于 2019-12-10 17:54:54

问题


Here is my code for the Force Download:

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

The Dialog Box that apears in Firefox says: You are going to open the file: And the filename is displayed just ass How (the name should be: How to use the Application.txt ). The sama I mentioned if I try to wright the filename for my self:

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

The same apears. Please Help!


回答1:


Mime files names should be double quoted.

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

This can be found in RFC 2616(HTTP 1.1)

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

Revised in RFC 6266 to allow file names without quotes too if they didn't contain disallowed charecters like spaces.

Content-Disposition: Attachment; filename=example.html




回答2:


You should put double quotes around the filename. Here is how to do that:

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

Note that I also changed your Strings upper/lower case to now "Content-Disposition", "attachment", "filename", "text/plain". You should use them in that way to not get into trouble with browsers that handle that quite strict.

If that doesn't work correctly, try:

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

Then the spaces in filenames are URL encoded.



来源:https://stackoverflow.com/questions/12000978/when-i-force-downloading-a-file-from-a-page-it-split-te-file-name-by-space-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!