FileDown(文件下载类)

using System;
using System.IO;
using System.Threading;
using System.Web;

/// <summary>
/// 文件下载类
/// </summary>
public class FileDown
{
    public FileDown()
    { }

/// <summary>
    /// 参数为虚拟路径
    /// </summary>
    public static string FileNameExtension(string FileName)
    {
        return Path.GetExtension(MapPathFile(FileName));
    }

/// <summary>
    /// 获取物理地址
    /// </summary>
    public static string MapPathFile(string FileName)
    {
        return HttpContext.Current.Server.MapPath(FileName);
    }

/// <summary>
    /// 普通下载
    /// </summary>
    /// <param name="FileName">文件虚拟路径</param>
    public static void DownLoadold(string FileName)
    {
        string destFileName = MapPathFile(FileName);
        if (File.Exists(destFileName))
        {
            FileInfo fi = new FileInfo(destFileName);
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.Buffer = false;
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Path.GetFileName(destFileName), System.Text.Encoding.UTF8));
            HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            HttpContext.Current.Response.WriteFile(destFileName);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
    }

/// <summary>
    /// 分块下载
    /// </summary>
    /// <param name="FileName">文件虚拟路径</param>
    public static void DownLoad(string FileName)
    {
        string filePath = MapPathFile(FileName);
        long chunkSize = 204800;             //指定块大小
        byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区
        long dataToRead = 0;                 //已读的字节数  
        FileStream stream = null;
        try
        {
            //打开文件  
            stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            dataToRead = stream.Length;

//添加Http头  
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(Path.GetFileName(filePath)));
            HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());

while (dataToRead > 0)
            {
                if (HttpContext.Current.Response.IsClientConnected)
                {
                    int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
                    HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                    HttpContext.Current.Response.Flush();
                    HttpContext.Current.Response.Clear();
                    dataToRead -= length;
                }
                else
                {
                    dataToRead = -1; //防止client失去连接
                }
            }
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write("Error:" + ex.Message);
        }
        finally
        {
            if (stream != null) stream.Close();
            HttpContext.Current.Response.Close();
        }
    }

/// <summary>
    ///  输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
    /// </summary>
    /// <param name="_Request">Page.Request对象</param>
    /// <param name="_Response">Page.Response对象</param>
    /// <param name="_fileName">下载文件名</param>
    /// <param name="_fullPath">带文件名下载路径</param>
    /// <param name="_speed">每秒允许下载的字节数</param>
    /// <returns>返回是否成功</returns>
    //---------------------------------------------------------------------
    //调用:
    // string FullPath=Server.MapPath("count.txt");
    // ResponseFile(this.Request,this.Response,"count.txt",FullPath,100);
    //---------------------------------------------------------------------
    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 = (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;
    }
}

时间: 2024-10-14 19:44:32

FileDown(文件下载类)的相关文章

php 支持断点续传的文件下载类

php 支持断点续传的文件下载类 分类: php class2013-06-30 17:27 17748人阅读 评论(6) 收藏 举报 php断点续传下载http测试 php 支持断点续传,主要依靠HTTP协议中 header HTTP_RANGE实现. HTTP断点续传原理Http头 Range.Content-Range()HTTP头中一般断点下载时才用到Range和Content-Range实体头,Range用户请求头中,指定第一个字节的位置和最后一个字节的位置,如(Range:200-3

文件下载类大全

<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /* $download = new download('php,exe,html',false); $this->load->library('Download'); if(!$this->download->->downloadfile($filename)) { echo $this->download->g

php实现的支持断点续传的文件下载类

通常来说,php支持断点续传,主要依靠HTTP协议中 header HTTP_RANGE实现. HTTP断点续传原理: Http头 Range.Content-Range()HTTP头中一般断点下载时才用到Range和Content-Range实体头,Range用户请求头中,指定第一个字节的位置和最后一个字节的位置,如(Range:200-300)Content-Range用于响应头 请求下载整个文件: GET /test.rar HTTP/1.1 Connection: close Host:

FileDown.cs(20170223)

using System; using System.IO; using System.Threading; using System.Web; namespace System.CRM.Common { /// <summary> /// 文件下载类 /// </summary> public class FileDown { public FileDown() { } /// <summary> /// 参数为虚拟路径 /// </summary> pu

新写PHP HTTP断点续传类文件代码

一个支持断点续传的PHP文件下载类文件,调用方法简单,类代码简洁,可记忆上次的下载的节点,实现累积下载,类名称download,类代码如下: function download($path,$file) { $real = $path.'/'.$file; if(!file_exists($real)) { return false; } $size = filesize($real); $size2 = $size-1; $range = 0; if(isset($_SERVER['HTTP_

Java Web文件下载

Web文件下载有两种,一种是文件在网站目录下,在浏览器中直接输入文件路径即可下载,如http://www.xxx.com/file.zip.另外一种是文件不在网站目录下或者文件是动态生成的(导出报表或者导出excel等),这种情况需要通过response的OutputStream实现文件的下载.DownloadUtils是一个Java Web文件下载工具类,提供多种静态方法实现文件下载. package com.rhui.util; import java.io.BufferedInputStr

php实现文件下载代码一例

php实现文件下载代码 php实现文件下载我们需要用到header函数来发送相关信息给客户端浏览器,同时再结合filesize函数来读取文件大小并进行下载操作.简单的文件下载只需要使用HTML的连接标记<a>,并将属性href的URL值指定为下载的文件即可. 文件下载,只能处理一些浏览器不能默认识别的MIME类型文件,例如当访问book.rar文件时,浏览器并没有直接打开,而是弹出一个下载提示框,提示用户“下载”还是“打开”等处理方式.但如果需要下载后缀名为.html的网页文件.图片文件及PH

各种帮助类

转自与网络 1 /// <summary> 2 /// web.config操作类 3 /// </summary> 4 public sealed class ConfigHelper 5 { 6 /// <summary> 7 /// 得到AppSettings中的配置字符串信息 8 /// </summary> 9 /// <param name="key"></param> 10 /// <retur

多线程断点续传及下载

断点下载 package com.example.downloaddemo; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import android.os.Bundle; import android.os.Handler; import android.os.