代码之家  ›  专栏  ›  技术社区  ›  Josh Bush

在asp.net中为动态PDF指定文件名

  •  37
  • Josh Bush  · 技术社区  · 17 年前

    在将数据转储到响应流中时,如何指定文件名?

    现在我正在做以下事情:

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

    使用上面的代码,我得到“foo.aspx.pdf”作为要保存的文件名。我似乎记得能够在响应中添加一个标题来指定要保存的文件名。

    5 回复  |  直到 17 年前
        1
  •  60
  •   Dan F    14 年前

    在标题中添加内容处置:

    Response.AddHeader("content-disposition", @"attachment;filename=""MyFile.pdf""");
    
        2
  •  20
  •   EMR    12 年前

    FYI。..如果你使用“内联”而不是“附件”,文件将在IE中自动打开。而不是用“打开/保存”对话框提示用户。

    Response.AppendHeader("content-disposition", string.Format("inline;FileName=\"{0}\"", fileName));
    
        3
  •  15
  •   Sklivvz    17 年前
    Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");
    
        4
  •  2
  •   Sam    10 年前

    出于某种原因,大多数答案似乎甚至没有尝试对文件名值进行编码。如果文件包含空格、分号或引号,则可能无法正确显示。

    看起来你可以使用 ContentDisposition 类以生成正确的标头值:

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

    您可以查看 the source code for ContentDisposition.ToString() 确认它正在尝试正确编码。

    警告 :当文件名包含破折号(不是连字符)时,这似乎会崩溃。我还没有费心去调查这件事。

        5
  •  1
  •   Kibbee    17 年前
     Response.AddHeader("Content-Disposition", "attachment;filename=" & FileName & ";")
    
    推荐文章