【问题标题】:How to download PDF file from files on button click?如何通过单击按钮从文件中下载 PDF 文件?
【发布时间】:2014-06-25 06:52:37
【问题描述】:

我想通过单击按钮下载 PDF 文件。我试过这样:

 protected void lbtnDownload_Click(object sender, EventArgs e)
    {
        if (lbtnDownload.Text != string.Empty)
        {
            else if (lbtnDownload.Text.EndsWith(".pdf"))
            {
                Response.ContentType = "application/pdf";
            }

            string filePath = lbtnDownload.Text;

            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
            Response.TransmitFile(HttpContext.Current.Server.MapPath("~/") + "\\PDF\\" + filePath );
            Response.End();
        }

    }

但是什么都没有发生,我的意思是当我调试它时没有异常,但是文件没有下载。

有谁知道我的错误在哪里,我应该怎么做才能下载 PDF?

【问题讨论】:

  • 文件应该从哪里下载?它是 UAC-Path(如 \\Computername\anyshare\anyfile.extension)还是 HTTP 服务器? (如anysite.tld/file.ext127.0.0.1/file.ext
  • 它是一个 UAC-Path 而不是 HTTP 服务器
  • 尝试在Response.End();之前添加Response.Flush();
  • 我在控制台中收到此错误:- 未捕获的 Sys.WebForms.PageRequestManagerParserErrorException:Sys.WebForms.PageRequestManagerParserErrorException:无法解析从服务器收到的消息。
  • 我修好了。问题出在我使用的 UpdatePanel 上。我添加了一个 PostBackTrigger,现在一切正常。谢谢

标签: c# pdf


【解决方案1】:

试试这个

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if(string.IsNullOrEmpty(txtName.Text)) return;            

        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + txtName.Text);
        string filePath = Server.MapPath(Path.Combine("~/SavedFolder/PDF", txtName.Text));
        Response.TransmitFile(filePath);
        Response.End();
    }

【讨论】:

  • 我没有“组合”选项.. :( 我不能使用 Path.Combine
  • 它位于 System.IO 命名空间 System.IO.Path.Combine,或者您可以将其替换为 "~/SavedFolder/PDF/" + txtName.Text
  • 我修好了。问题出在我使用的 UpdatePanel 上。我添加了一个 PostBackTrigger,现在一切正常。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
相关资源
最近更新 更多