Cheng Chen
Cheng Chen

Reputation: 43531

Is it necessary to url encode the file name?

In my asp.net mvc application I have the code:

response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", "attachment;filename=" + 
    HttpUtility.UrlEncode(attachment.FileName));

So that all the Chinese characters are url-encoded to something like %5C%2D. In IE/Chrome when users download the file, they get the Chinese file name(that is, IE/Chrome will automatically url-decode the file name). But in Firefox, they will get something like %5C%2D%0A.docx. Now I'm going to remove HttpUtility.UrlEncode in the code. But before doing this, I want to confirm that there is no security issues in this case. Would you please give me some ideas?

EDIT Corbin's answer is correct. But after removing the url-encoding of the filename, some users using old version IE will get strange messy file names. At last I do url-encode for those users only.

Upvotes: 3

Views: 7105

Answers (3)

Nguyễn Văn Quang
Nguyễn Văn Quang

Reputation: 29

please change your code as follow:

if (Request.Browser.Browser == "IE" || Request.Browser.Browser == "Chrome")
{
    filename = HttpUtility.UrlPathEncode(filename);
}
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

notes: your code miss "\"" for wrap file name in quotes

Upvotes: 3

Boris Zbarsky
Boris Zbarsky

Reputation: 35084

The name is allowed to be in quotes if it's ASCII.

If it's non-ASCII, then you have to use the encoding defined in RFC 2231 or the one in RFC 5987 or the one in RFC 2047... which browsers support which of these is a fun game, of course. :(

If you just stick the raw non-ASCII bytes into the header, it will almost certainly look like garbage for a large fraction of users.

Upvotes: 3

Corbin
Corbin

Reputation: 33467

http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html

Unless I'm misunderstanding it, it looks like the name should just be in quotes, not url encoded.

Upvotes: 2

Related Questions