我使用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();行
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();
:
答案 0 :(得分:0)
我不确定错误消息的意图但是我通过测试来查看消息是否包含“正在中止线程”消息。这是一个例子:
if (ex.Message.StartsWith("Thread") == false)
{
Response.Redirect("~/Error.aspx?ErrorMsg = " + ex.Message);
}
此外,
请检查此链接原因和错误解决方案:http://support.microsoft.com/kb/312629/EN-US/
答案 1 :(得分:0)
我不知道这是否可以帮助你,从流中打开PDF文件我使用下面的代码,对我来说很好,并且不会触发任何异常。我从db获取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();