asp.net下载文件

原文:http://www.renfb.com/blog/2011/Article/29

通常下载文件的方法是直接链接到文件的实际url地址,这样的方法很简单,实用,不过唯一的缺点是无法统计文件下载的次数。而微软提供的Response.WriteFile方法下载文件虽然可以统计到文件的下载次数,却不能下载大文件(微软提供了response.transmitfile用来下载大文件,对这个方法不太熟悉)。通过网上寻求解决方法,发现通过流方式下载文件,不仅可以控制下载速度,而且可以对要下载的文件有更好的控制。下面列出实现方法。

        
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;
using System.IO;
using System.Threading;

///
/// Downloads 的摘要说明
///
public class Downloads
{
	public Downloads()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//
	}

    public static HttpResponse Response
    {
        get
        {
            return HttpContext.Current.Response;
        }
    }

    public static HttpRequest Request
    {
        get
        {
            return HttpContext.Current.Request;
        }
    }

    private static long _speed = 1024000000;
    public static long Speed
    {
        get
        {
            return _speed;
        }
        set
        {
            _speed = value;
        }
    }

    public static bool DownLoad(string filepath)
    {
        string filename = System.IO.Path.GetFileName(filepath);
        try
        {
            FileStream myFile = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try
            {
                Response.Clear();
                Response.AddHeader("Accept-Ranges", "bytes");
                Response.Buffer = false;
                long fileLength = myFile.Length;
                long startBytes = 0;

                int pack = 10240000;   //10K   bytes
                //int   sleep   =   200;   //每秒5次   即5*10K   bytes每秒
                int sleep = (int)Math.Floor((double)(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((double)((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;
    }
}
         

      可以将Downloads类拷贝到App_Code,然后直接使用Downloads.DownLoad(文件的绝对地址)即可下载文件。也可以将该类修改为自己需要的任何形式进行使用。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值