【问题标题】:Download PDF file from a Directory Listing从目录列表下载 PDF 文件
【发布时间】:2014-10-13 18:48:54
【问题描述】:

我使用 Gridview 控件在 asp.net webforms 中显示目录的内容。

过滤内容以仅显示 PDF 文件。

我在 TemplateField 中也有一个按钮。单击按钮后,用户应该能够下载并保存 PDF 文件。

Gridview 中显示的列是文件名、修改日期和大小。

如何编程按钮单击以下载和保存 PDF 文件?

【问题讨论】:

  • 请发布您的 gridview 标记和文件保存位置

标签: c# asp.net gridview webforms


【解决方案1】:

在您的Button 点击事件中,编写以下代码。

protected void Button1_Click(object sender, EventArgs e) 
{ 
    Response.ContentType = "Application/pdf"; 
    Response.AppendHeader("Content-Disposition", "attachment; filename=Your_Pdf_File.pdf"); 
    Response.TransmitFile(Server.MapPath("~/Files/Your_Pdf_File.pdf"));
    Response.End(); 
} 

【讨论】:

    【解决方案2】:

    我有一个执行文件下载的函数。

    public static void DownloadFile(string FilePath, System.Web.HttpResponse response)
    {
        System.IO.FileInfo file = new System.IO.FileInfo(FilePath);
        if ((file.Exists))
        {
            response.Clear();
            response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
            response.AddHeader("Content-Length", file.Length.ToString());
            response.ContentType = "application/octet-stream";
            response.WriteFile(file.FullName);
            response.End();
            response.Close();
            file = null;
        }
    }
    

    FilePath参数是物理路径,所以如果你有虚拟路径(例如~/Folder/file.pdf)可能需要使用Server.MapPath(...)函数来调用函数。

    【讨论】:

    • 感谢您的建议。
    • 如何从 Gridview 获取文件名?
    • 我以 Scott 的这篇文章为出发点。 4guysfromrolla.com/articles/090110-1.aspx
    • 能把GridView的代码和后面的相关代码贴出来吗?没有这些,就不容易回答了..
    猜你喜欢
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多