Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Filename encoding while sending file

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

like image 941
pkolodziej Avatar asked Dec 08 '22 05:12

pkolodziej


2 Answers

Put the file name in quotes:-

Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
like image 170
AnthonyWJones Avatar answered Dec 11 '22 12:12

AnthonyWJones


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.

like image 26
bobince Avatar answered Dec 11 '22 10:12

bobince