1. 程式人生 > >ASP.NET DEV 前端利用後端方法顯示PDF檔案連結地址,點選下載

ASP.NET DEV 前端利用後端方法顯示PDF檔案連結地址,點選下載

主要功能說明:前端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("檔案不存在!");
            }
            
        }