Specifying filename for dynamic PDF in asp.net

How can I specify the filename when dumping data into the response stream?

Right now I’m doing the following:

byte[] data= GetFoo();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";            
Response.BinaryWrite(data);
Response.End();

With the code above, I get “foo.aspx.pdf” as the filename to save. I seem to remember being able to add a header to the response to specify the filename to save.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Add a content-disposition to the header:

Response.AddHeader("content-disposition", @"attachment;filename=""MyFile.pdf""");

Method 2

FYI… if you use “inline” instead of “attachment” the file will open automatically in IE. Instead of prompting the user with a Open/Save dialogue.

Response.AppendHeader("content-disposition", string.Format("inline;FileName="{0}"", fileName));

Method 3

Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");

Method 4

For some reason, most of the answers out there don’t seem to even attempt to encode the file name value. If the file contains spaces, semicolons or quotes, it mightn’t come across correctly.

It looks like you can use the ContentDisposition class to generate a correct header value:

Response.AppendHeader("Content-Disposition", new ContentDisposition
{
    FileName = yourFilename
}.ToString());

You can check out the source code for ContentDisposition.ToString() to confirm that it’s trying to encode it properly.

Warning: This seems to crash when the filename contains a dash (not a hyphen). I haven’t bothered looking into this yet.

Method 5

 Response.AddHeader("Content-Disposition", "attachment;filename=" & FileName & ";")


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x