C# 在 asp.net 中为动态 PDF 指定文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/74019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Specifying filename for dynamic PDF in asp.net
提问by Josh Bush
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.
使用上面的代码,我将“foo.aspx.pdf”作为要保存的文件名。我似乎记得能够在响应中添加一个标头以指定要保存的文件名。
采纳答案by Ryan Farley
Add a content-disposition to the header:
向标题添加内容处置:
Response.AddHeader("content-disposition", @"attachment;filename=""MyFile.pdf""");
回答by Sklivvz
Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");
回答by Kibbee
Response.AddHeader("Content-Disposition", "attachment;filename=" & FileName & ";")
回答by EMR
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.
仅供参考...如果您使用“内联”而不是“附件”,该文件将在 IE 中自动打开。而不是通过打开/保存对话框提示用户。
Response.AppendHeader("content-disposition", string.Format("inline;FileName=\"{0}\"", fileName));
回答by Sam
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:
看起来您可以使用ContentDisposition
该类生成正确的标头值:
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.
您可以查看源代码ContentDisposition.ToString()
以确认它正在尝试正确编码。
Warning: This seems to crash when the filename contains a dash (not a hyphen). I haven't bothered looking into this yet.
警告:当文件名包含破折号(不是连字符)时,这似乎会崩溃。我还没有费心研究这个。