2010-07-01 164 views

回答

12

是的,有几种方法可以做到这一点。这里是你如何做到这一点。

不要使用直接链接像<a href="http://mysite.com/music/song.mp3"></a>那样从磁盘提供mp3文件,请编写HttpHandler来提供文件下载。在HttpHandler中,您可以更新数据库中的文件下载计数。

文件下载的HttpHandler

//your http-handler 
public class DownloadHandler : IHttpHandler 
{ 
    public void ProcessRequest(HttpContext context) 
    { 
     string fileName = context.Request.QueryString["filename"].ToString(); 
     string filePath = "path of the file on disk"; //you know where your files are 
     FileInfo file = new System.IO.FileInfo(filePath); 
     if (file.Exists) 
     { 
      try 
      { 
       //increment this file download count into database here. 
      } 
      catch (Exception) 
      { 
       //handle the situation gracefully. 
      } 
      //return the file 
      context.Response.Clear(); 
      context.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); 
      context.Response.AddHeader("Content-Length", file.Length.ToString()); 
      context.Response.ContentType = "application/octet-stream"; 
      context.Response.WriteFile(file.FullName); 
      context.ApplicationInstance.CompleteRequest(); 
      context.Response.End(); 
     } 
    } 
    public bool IsReusable 
    { 
     get { return true; } 
    } 
} 

Web.config配置

//httphandle configuration in your web.config 
<httpHandlers> 
    <add verb="GET" path="FileDownload.ashx" type="DownloadHandler"/> 
</httpHandlers> 

从前端链接文件下载

//in your front-end website pages, html,aspx,php whatever. 
<a href="FileDownload.ashx?filename=song.mp3">Download Song3.mp3</a> 

此外,您可以将web.config中的mp3扩展名映射到HttpHandler。要做到这一点,您必须确保,您将IIS配置为将.mp3扩展请求转发到asp.net工作进程,而不是直接提供服务,并且确保mp3文件不在处理程序捕获的相同位置,如果在同一位置的磁盘上找到该文件,则HttpHandler将被覆盖并且该文件将从磁盘提供。

<httpHandlers> 
    <add verb="GET" path="*.mp3" type="DownloadHandler"/> 
</httpHandlers> 
+0

如果您的解决方案存在问题,但是在阅读完此相关问题后立即解决:http://stackoverflow.com/questions/460301/httphandler-101-fail – 2010-07-02 03:03:43

2

你可以做的是,你创建一个通用处理器(* .ashx的文件),然后访问通过文件:

Download.ashx文件= somefile.mp3

在处理程序中,您可以运行代码,记录访问并将文件返回给浏览器。
请确保您执行了正确的安全检查,因为这可以用于访问您的Web目录中的任何文件甚至整个文件系统!

如果你知道你的所有文件都是* .MP3,第二个选项是添加到您的web.config文件的httpHandlers一节:

<add verb="GET" path="*.mp3" type="<reference to your Assembly/HttpHandlerType>" /> 

和运行代码在你的HttpHandler。

1

使用HttpHandler进行下载计数的问题在于,它会在有人开始下载文件的时候触发。但许多互联网蜘蛛,搜索引擎等将刚刚开始下载,并很快取消它!你会在下载文件时被注意到。

更好的方法是制作一个分析你的IIS统计文件的应用程序。所以你可以检查用户下载的字节数。如果字节相同或大于文件大小,则表示用户下载完整文件。其他尝试只是企图。