views:

726

answers:

4

Hi

I am sending a file from ASP.NET Page to the browser. To properly send a filename I am adding a header:

Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);

The problem is that when file contains white spaces (e.g. "abc def") browser receives only "abc" part of the filename. I have tried with: Server.HtmlEncode but it didn't help.

Do you have any idea how to solve this problem?

PK

A: 

Server.UrlEncode

Arthur
+4  A: 

Put the file name in quotes:-

Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
AnthonyWJones
+2  A: 

Don't UrlEncode. This is not the right way to escape a value for use in an HTTP structured header parameter. It only works in IE due to that browser's buggy handling, and even then not reliably.

For a space you can use a quoted-string as suggested by Anthony (+1). But the dirty truth of Content-Disposition is that there is no reliable, supported escaping scheme that can be used to put arbitrary characters such as ;, " or Unicode characters in the filename parameter. The only approach that works reliably cross-browser is to drop the filename parameter completely and put the desired filename in the URI as a trailing, UTF-8+URL-encoded path part.

See this answer for some background.

bobince
Typically in a windows environment ; isn't a valid filename character anyway. I tend to put anything that uses this filename parameter through a "legal-in-filename" sanitizer to take out such characters.
AnthonyWJones
A: 

Filename with special symbols(e.g: space; # @ ! $ ) or Non-Unicode characters either cannot be supported by some browsers or cause incorrect filename in client machine. Here is an article by a Chinese called chanext, he gave a perfect way to solve this fucking problem: this article gave a sample code(written with c#) to show how to get perfect solution to this problem in the all four popular browsers (IE; Opera; Firefox and Chrome) the filename "Microsoft.Asp.Net.doc" and "F ile;;!@%#^&y.doc" can both be output correctly using the way the author provided in this article.

http://ciznx.com/post/aspnetstreamdownloaddisplaynonunicodespacechar.aspx

chanext