1

我正在使用 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 iam 时出现错误:

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

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

4

2 回答 2

0

I'm not exactly sure of the intent of the error message but I got around the error by testing to see if the message contains the "Thread is being aborted" message. Here's an example:

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

Also,

Please check this link reason and solution of the error: http://support.microsoft.com/kb/312629/EN-US/

于 2013-10-25T05:52:33.700 回答
0

我不知道这是否可以帮助您,从流中打开 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();
于 2013-10-25T06:10:20.333 回答