代码之家  ›  专栏  ›  技术社区  ›  Sam Cromer

asp.net中的文件处理程序

  •  1
  • Sam Cromer  · 技术社区  · 11 年前

    我需要跟踪pdf文件何时在我的网络应用程序中打开。现在,当用户点击链接,然后从后面的代码中使用window.open时,我正在写入数据库,这并不理想,因为Safari会阻止弹出窗口,其他网络浏览器在运行时会发出警告,所以我想我需要使用文件处理程序吗。我以前没有使用过文件处理程序,所以这是可行的吗?pdf不是二进制形式的,它只是一个位于目录中的静态文件。

    2 回复  |  直到 11 年前
        1
  •  4
  •   pedrommuller    11 年前

    创建一个ASHX(比aspx onload事件更快)页面,将文件的id作为查询字符串传递以跟踪每次下载

     public class FileDownload : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
            {
                //Track your id
                string id = context.Request.QueryString["id"];
                //save into the database 
                string fileName = "YOUR-FILE.pdf";
                context.Response.Clear();
                context.Response.ContentType = "application/pdf";
                context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                context.Response.TransmitFile(filePath + fileName);
                context.Response.End();
               //download the file
            }
    

    在你的html中应该是这样的

    <a href="/GetFile.ashx?id=7" target="_blank">
    

    window.location = "GetFile.ashx?id=7";
    

    但我更愿意坚持链接解决方案。

        2
  •  4
  •   MikeSmithDev    11 年前

    以下是自定义HttpHandler的一个选项,该选项使用PDF的常规锚标记:

    创建ASHX(右键单击项目->添加新项目-<通用处理程序)

    using System.IO;
    using System.Web;
    
    namespace YourAppName
    {
        public class ServePDF : IHttpHandler
        {
            public void ProcessRequest(HttpContext context)
            {
                string fileToServe = context.Request.Path;
                //Log the user and the file served to the DB
                FileInfo pdf = new FileInfo(context.Server.MapPath(fileToServe));
                context.Response.ClearContent();
                context.Response.ContentType = "application/pdf";
                context.Response.AddHeader("Content-Disposition", "attachment; filename=" + pdf.Name);
                context.Response.AddHeader("Content-Length", pdf.Length.ToString());
                context.Response.TransmitFile(pdf.FullName);
                context.Response.Flush();
                context.Response.End();
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
    

    编辑web.config以将处理程序用于所有PDF:

    <httpHandlers>
        <add verb="*" path="*.pdf" type="YourAppName.ServePDF" />
    </httpHandlers>
    

    现在,到PDF的常规链接将使用您的处理程序来记录活动并提供文件

    <a href="/pdf/Newsletter01.pdf">Download This</a>