【发布时间】:2012-04-09 22:59:30
【问题描述】:
我正在尝试在代码隐藏中使用锚点,并在单击该锚点时下载 pdf。我下载的东西在页面加载时工作正常,但我不确定如何设置 onlick 以下载 pdf。
HtmlAnchor apdf = new HtmlAnchor();
apdf.ID = Guid.NewGuid().ToString("N");
apdf.InnerText = dsreport.Tables[0].Rows[0]["ImageName"].ToString();
apdf.Attributes.Add("style", "font-weight: bold; font-size: 13px; margin: 0px;font-family: Arial; color: #1e7c9b; text-decoration: underline");
apdf.Attributes.Add("onclick", "");
对于每次点击,我必须设置下面的代码,所以 PDF 只在点击时下载。
byte[] aByteArrayOfTheFile = (byte[])(dsreport.Tables[0].Rows[0]["ImageData"]);
SendAsFileToBrowser(aByteArrayOfTheFile, "application/pdf", "downloaded.pdf");
更新:
public static string SendAsFileToBrowser(byte[] File, string Type, string FileName)
{
string disp = "attachment";
if (string.IsNullOrEmpty(FileName))
{
disp = "inline";
}
// set headers
//char r = HttpContext.Current.Response;
HttpContext.Current.Response.ContentType = Type; // eg "image/Png"
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Type", "binary/octet-stream");
HttpContext.Current.Response.AddHeader("Content-Length", File.Length.ToString());
HttpContext.Current.Response.AddHeader("Content-Disposition", disp + "; filename=" + FileName + "; size=" + File.Length.ToString());
HttpContext.Current.Response.Flush();
// write data to requesting browser
HttpContext.Current.Response.BinaryWrite(File);
HttpContext.Current.Response.Flush();
return "";
}
使用它会在页面加载时打开,而不是在 Onclick 上。只想在用户点击时下载。
我在 VS 2005 和 sql server 2005 中使用 c# 2.0。在后面的代码中设置 onclick 真是让我头疼。提前感谢您的帮助!
【问题讨论】: