【问题标题】:issue when downloading pdf in asp.net在asp.net中下载pdf时的问题
【发布时间】:2013-11-04 02:30:25
【问题描述】:

我正在使用 asp.net 中的以下代码下载 PDF

 try
            {
                string strURL = Directory.GetFiles(Server.MapPath("PDFs/PrintPDF")).SingleOrDefault();

                WebClient req = new WebClient();
                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.ClearContent();
                response.ClearHeaders();
                response.Buffer = true;
                response.AddHeader("Content-Disposition", "attachment;filename=\"" + strURL + "\"");
                byte[] data = req.DownloadData(strURL);
                response.BinaryWrite(data);
                response.End();//At this line I am getting the error

            }
            catch (Exception ex)
            {
            }

上面的代码正在运行。但是去 Catch Block 并显示错误:

"[System.Threading.ThreadAbortException] = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}"

我已经用这条线替换了 response.End();line

HttpContext.Current.ApplicationInstance.CompleteRequest();

正在下载 PDF,但无法打开 PDF。打开 PDF 时出现错误:

"there was an error opening this document. the file is damaged and could not be repaired"

我也尝试在没有帮助的情况下使用response.Flush();

【问题讨论】:

    标签: c# asp.net pdf download


    【解决方案1】:

    我不完全确定错误消息的意图,但我通过测试查看消息是否包含“线程正在中止”消息解决了该错误。这是一个例子:

            if (ex.Message.StartsWith("Thread") == false)
            {
                Response.Redirect("~/Error.aspx?ErrorMsg = " + ex.Message);
            }
    

    还有,

    请查看此链接原因及错误解决方法:http://support.microsoft.com/kb/312629/EN-US/

    【讨论】:

      【解决方案2】:

      我不知道这是否可以帮助您,要从流中打开 PDF 文件,我使用以下代码对我来说很好,并且不会引发任何异常。我从数据库中获取我的 pdf,对于 pdf 文件,我不使用 addHeader。希望对你有帮助。

      Response.ClearContent();
      Response.ClearHeaders();
      Response.ContentType = "application/pdf";
      var abyt = (Byte[]) ds.Tables[0].Rows[0]["blob"];
      Response.BinaryWrite(abyt);
      Response.Flush();
      Response.Close();
      

      【讨论】:

        猜你喜欢
        • 2022-10-14
        • 1970-01-01
        • 2019-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多