ASP.NET HttpHandler multi-use file extensions download reprint

Reprinted from: http://www.cnblogs.com/liping13599168/archive/2009/02/08/1386111.html

1. First create a page for page download process, such as download.aspx, which did nothing.

2. Add DownloadHandler a class that inherits from IHttpHandler interface can be used to customize the HTTP handler synchronization processing HTTP requests.

public   class  DownloadHandler : IHttpHandler
{
    
public   void  ProcessRequest(HttpContext context)
    {
        HttpResponse Response 
=  context.Response;
        HttpRequest Request 
=  context.Request;

        System.IO.Stream iStream 
=   null ;

        
byte [] buffer  =   new  Byte[ 10240 ];

        
int  length;

        
long  dataToRead;

        
try
        {
            
string  filename  =  FileHelper.Decrypt(Request[ " fn " ]);  // obtained by the decryption file name String  filepath  =  HttpContext.Current.Server.MapPath ( " ~ / " + " Files / " +  filename;  // file path to be downloaded             iStream  = new new  System.IO.FileStream (filepath, the System .IO.FileMode.Open,                 System.IO.FileAccess.Read, System.IO.FileShare.Read);             Response.Clear ();             dataToRead  =  iStream.Length; Long  P  = 0 ; IF  (Request.Headers [ " the Range "

            
   

 





            
 
            
!=   null )
            {
                Response.StatusCode 
=   206 ;
                p 
=   long .Parse(Request.Headers[ " Range " ].Replace( " bytes= " "" ).Replace( " - " "" ));
            }
            
if  (p  !=   0 )
            {
                Response.AddHeader(
" Content-Range " " bytes  "   +  p.ToString()  +   " - "   +  (( long )(dataToRead  -   1 )).ToString()  +   " / "   +  dataToRead.ToString());
            }
            Response.AddHeader(
" Content-Length " , (( long )(dataToRead  -  p)).ToString());
            Response.ContentType 
=   " application/octet-stream " ;
            Response.AddHeader(
" Content-Disposition " " attachment; filename= "   +  System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding( 65001 ).GetBytes(Path.GetFileName(filename))));

            iStream.Position 
=  p;
            dataToRead 
=  dataToRead  -  p;

            
while  (dataToRead  >   0 )
            {
                
if  (Response.IsClientConnected)
                {
                    length 
=  iStream.Read(buffer,  0 10240 );

                    Response.OutputStream.Write(buffer, 
0 , length);
                    Response.Flush();

                    buffer 
=   new  Byte[ 10240 ];
                    dataToRead 
=  dataToRead  -  length;
                }
                
else
                {
                    dataToRead 
=   - 1 ;
                }
            }
        }
        
catch  (Exception ex)
        {
            Response.Write(
" Error :  "   +  ex.Message);
        }
        
finally
        {
            
if  (iStream  !=   null )
            {
                iStream.Close();
            }
            Response.End();
        }
    }

    
public   bool  IsReusable
    {
        
get  {  return   true ; }
    }
}


3. This involves the problem of a file name to encryption and decryption, in order to prevent specific file name in the status bar is exposed, so add a FileHelper class, as follows:

public   class  FileHelper
{
    
public   static   string  Encrypt( string  filename)
    {
        
byte [] buffer  =  HttpContext.Current.Request.ContentEncoding.GetBytes(filename);
        
return  HttpUtility.UrlEncode(Convert.ToBase64String(buffer));
    }

    
public   static   string  Decrypt( string  encryptfilename)
    {
        
byte [] buffer  =  Convert.FromBase64String(encryptfilename);
        
return  HttpContext.Current.Request.ContentEncoding.GetString(buffer);
    }
}

File name encryption and decryption process use Base64 code.

4. On the Web.config, add httpHandlers node, as follows:

< system.web >
  dot.gif
  
< httpHandlers >
    
< add  verb ="*"  path ="download.aspx"  type ="DownloadHandler"   />
  
</ httpHandlers >
</ system.web >


5. Now create a new aspx page, download the file:

Default.aspx code is as follows:

ContractedBlock.gif ExpandedBlockStart.gif Default.aspx Code
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><</Downloads>title  

 

 

    
title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
    
<asp:HyperLink ID="link" runat="server" Text="文件下载"></asp:HyperLink>
    
</div>
    
</form>
</body>
</html>

 

Default.aspx.cs code is as follows:

ContractedBlock.gif ExpandedBlockStart.gif Default.aspx.cs Code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls; 

public partial class _Default : System.Web.UI.Page 
{
    
protected void Page_Load(object sender, EventArgs e)
    {
        
string url = FileHelper.Encrypt("DesignPattern.chm");
        link.NavigateUrl 
= "~/download.aspx?fn=" + url;
    }
}

Reproduced in: https: //www.cnblogs.com/daretodream/archive/2010/08/03/1791186.html

Guess you like

Origin blog.csdn.net/weixin_34342578/article/details/93324150