zoukankan      html  css  js  c++  java
  • ASP.NET提供文件下载函数(支持大文件、续传、速度限制、资源占用小)

     // 输出硬盘文件,提供下载
      
    // 输入参数 _Request: Page.Request对象,  _Response: Page.Response对象, _fileName: 下载文件名, _fullPath: 带文件名下载路径, _speed 每秒允许下载的字节数
      
    // 返回是否成功
      public static bool ResponseFile(HttpRequest _Request,HttpResponse _Response,string _fileName,string _fullPath, long _speed)
      {
       
    try
       {
        FileStream myFile 
    = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        BinaryReader br 
    = new BinaryReader(myFile);
        
    try
        {
         _Response.AddHeader(
    "Accept-Ranges""bytes");
         _Response.Buffer 
    = false;
         
    long fileLength = myFile.Length;
         
    long startBytes = 0;
         
         
    int pack = 10240//10K bytes
         
    //int sleep = 200;   //每秒5次   即5*10K bytes每秒
         int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
         
    if (_Request.Headers["Range"!= null)
         {
          _Response.StatusCode 
    = 206;
          
    string[] range = _Request.Headers["Range"].Split(new char[] {'=''-'});
          startBytes 
    = Convert.ToInt64(range[1]);
         }
         _Response.AddHeader(
    "Content-Length", (fileLength - startBytes).ToString());
         
    if (startBytes != 0)
         {
          _Response.AddHeader(
    "Content-Range"string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
         }
         _Response.AddHeader(
    "Connection""Keep-Alive");
         _Response.ContentType 
    = "application/octet-stream";
         _Response.AddHeader(
    "Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(_fileName,System.Text.Encoding.UTF8) );
     
         br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
         
    int maxCount = (int) Math.Floor((fileLength - startBytes) / pack) + 1;

         
    for (int i = 0; i < maxCount; i++)
         {
          
    if (_Response.IsClientConnected)
          {
           _Response.BinaryWrite(br.ReadBytes(pack));
           Thread.Sleep(sleep);
          }
          
    else
          {
           i
    =maxCount; 
          }
         }
        }
        
    catch
        {
         
    return false;
        }
        
    finally
        {
         br.Close();
         myFile.Close();
        }
       }
       
    catch
       {
        
    return false;
       }
       
    return true;
      }

    调用例

       Page.Response.Clear();
         
       bool success = ResponseFile(Page.Request, Page.Response, "filename", @"C:\download.date", 1024000);
      
       if(!success)
        Response.Write("下载文件出错!");
       Page.Response.End();


    作者Blog:http://blog.csdn.net/nickycheng/

    下面是vb.net 版本

            Public Function ResponseFile(ByVal FRequest As HttpRequest, ByVal FResponse As HttpResponse, ByVal fileName As StringByVal fullPath As StringByVal speed As LongAs Boolean
                
    Try
                    
    Dim myFile As FileStream = New FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
                    
    Dim br As BinaryReader = New BinaryReader(myFile)
                    
    Try
                        FResponse.AddHeader(
    "Accept-Ranges""bytes")

                        FResponse.Buffer 
    = False '關閉存後送出
                        Dim fileLength As Long = myFile.Length
                        
    Dim startBytes As Long = 0

                        
    Dim pack As Integer = 10240  '10K bytes
                        'int sleep = 200;   //每秒5次   即5*10K bytes每秒
                        Dim sleep As Integer = CType(Math.Floor(1000 * pack / speed) + 1Integer)
                        
    If (FRequest.Headers("Range"<> NothingThen
                            FResponse.StatusCode 
    = 206
                            
    Dim range() As String = FRequest.Headers("Range").Split(New Char() {"="c, "-"c})
                            startBytes 
    = Convert.ToInt64(range(1))

                        
    End If
                        FResponse.AddHeader(
    "Content-Length", (fileLength - startBytes).ToString())
                        
    If (startBytes <> 0Then
                            FResponse.AddHeader(
    "Content-Range"String.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength))
                        
    End If
                        FResponse.AddHeader(
    "Connection""Keep-Alive")
                        FResponse.ContentType 
    = "application/octet-stream"
                        FResponse.AddHeader(
    "Content-Disposition""attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8))

                        br.BaseStream.Seek(startBytes, SeekOrigin.Begin)
                        
    Dim maxCount As Integer = CType(Math.Floor((fileLength - startBytes) / pack) + 1Integer)
                        
    Dim i As Integer
                        
    For i = 0 To maxCount - 1 Step i + 1
                            
    If (FResponse.IsClientConnected) Then
                                FResponse.BinaryWrite(br.ReadBytes(pack))
                                Thread.Sleep(sleep)
                            
    Else
                                i 
    = maxCount
                            
    End If
                        
    Next
                    
    Catch
                        
    Return False
                    
    Finally
                        br.Close()
                        myFile.Close()
                    
    End Try
                
    Catch
                    
    Return False
                
    End Try
                
    Return True
            
    End Function
    調用時:
                Page.Response.Clear()
                Me.ResponseFile(Page.Request, Page.Response, filename, Server.MapPath(fileurl), 10240)
                Page.Response.End()

    申明

    非源创博文中的内容均收集自网上,若有侵权之处,请及时联络,我会在第一时间内删除.再次说声抱歉!!!

    博文欢迎转载,但请给出原文连接。

  • 相关阅读:
    QT4.7.1 + VS2008 + QT Designer开发流程心得
    SharePoint 2010 托管元数据Bug (跟邮件提醒功能相关.小bug,大问题)
    SharePoint 2010 技巧系列: 控制Ribbon菜单权限(SiteActions的例子)
    发布一个SharePoint 2010 工具(复制,移动文件和文件夹)
    SHarePoint 2010 技巧 列验证 (column Validation)
    SharePoint 2010系列: 教你如何创建Internet 站点一 (设计母版页)
    SharePoint2010 技巧系列:快速开发Ribbon
    SharePoint 2010 技巧: 限制People Picker搜索非站点集内的用户
    SharePoint 2010 技巧系列 启用文档库接收邮件功能
    SharePoint 2010 技巧系列: 文档管理的自动分发功能
  • 原文地址:https://www.cnblogs.com/Athrun/p/551971.html
Copyright © 2011-2022 走看看