ASP.NET DEV 前端利用后端方法显示PDF文件链接地址,点击下载

时间:2022-04-03 00:32:55

主要功能说明:前端GridViewDataTextColumn显示PDF文件下载地址,点击后下载该文件

代码:

<%# %>:调用后台方法,<Eval("")>:获取当前行中某单元数据

<dxwgv:GridViewDataTextColumn FieldName="SUMMARY" VisibleIndex="2" Caption="摘要"
Width="430" CellStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Center">
<DataItemTemplate>
<%#GetSummary(Eval("SUMMARY"), Eval("STATUS"), Eval("PLAN_ID"), Eval("CREATE_TIME"))%>
</DataItemTemplate>
</dxwgv:GridViewDataTextColumn>

后台显示文件链接方法:

public object GetSummary(object summary, object status, object planId, object createTime)
{
if (status.ToString() == "3")
{
string url = Server.MapPath("~\\\\SPCReports\\\\" + createTime.ToString().Substring(0, 4) + "\\\\" + planId + ".pdf");
string year = createTime.ToString().Substring(0, 4);
return "<a style=\"color: Blue; text-decoration: none;\" href=\"javascript:downLoadFile('" + year + "','" + planId.ToString() + "','" + summary.ToString() + "')\" >" + summary.ToString() + " </a>";
}
else
{
return summary.ToString();
}
}

文件下载JS方法:

function downLoadFile(year, planId, fileName) {
window.location.href = 'http://' + $('#FullPath').val() + "ashx/DownLoadPDFFile.ashx?year=" + year + "&planId=" + planId + "&fileName=" + fileName;
}
下载PDF方法:

public void ProcessRequest(HttpContext context)
{
string year = context.Request["year"];
string planId = context.Request["planId"];
string fileName = context.Request["fileName"];
string file = HttpContext.Current.Server.MapPath("~\\SPCReports\\" + year + "\\" + planId + ".pdf");
FileInfo fileInfo = new FileInfo(file);
if (System.IO.File.Exists(file))
{
context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName + ".pdf", System.Text.Encoding.UTF8));
context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
context.Response.AddHeader("Content-Transfer-Encoding", "binary");
context.Response.ContentType = "application/octet-stream";
context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
context.Response.WriteFile(fileInfo.FullName);
context.Response.Flush();
context.Response.End();
}
else
{
context.Response.Write("文件不存在!");
}

}