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>
        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;
        }

        /// <summary>
        /// 下载远程图片
        /// DownImage("http://portal.cjmex-jyds.cn/static/user_img/20160127044020_204558.jpg", @"C:\Users\Administrator\Downloads\20160127044020_204558.jpg");
        /// </summary>
        /// <param name="Url">Url地址</param>
        /// <param name="Path">保存路径</param>
        public static void DownImage(string Url, string Path)
        {
            System.Net.WebClient web = new System.Net.WebClient();
            web.DownloadFile(Url, Path);

        }

        /// <summary>
        /// 下载服务器上的图片(非远程)
        /// 此方式不适用ajax,如果用ajax的话没有下载提示。
        /// 在这里不作调用
        /// </summary>
        /// <param name="context"></param>
        public static void DownImage2(HttpContext context)
        {

            try
            {
                string FullFileName = context.Server.MapPath("files") + "\\4bed2e738bd4b31c5aec920185d6277f9f2ff8bc.jpg"; //FileName--要下载的文件名 服务器上的图
                FullFileName = FullFileName.Replace("\\web", "");
                System.IO.FileInfo DownloadFile = new System.IO.FileInfo(FullFileName);
                if (DownloadFile.Exists)
                {
                    context.Response.Clear();
                    context.Response.ClearHeaders();
                    context.Response.Buffer = false;
                    context.Response.ContentType = "application/octet-stream";
                    context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.Name, System.Text.Encoding.ASCII));
                    context.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
                    context.Response.WriteFile(DownloadFile.FullName);
                    context.Response.Flush();
                    context.Response.End();
                }
                else
                {
                    //文件不存在
                }
            }
            catch
            {
                //文件不存在
            }
        }
    }
}
时间: 2024-10-10 14:49:11

FileDown.cs(20170223)的相关文章

CookieHelper.cs(20170223)

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace System.CRM.Common { /// <summary> /// Cookie操作助手类 /// </summary> public class CookieHelper { /// &l

CS文件类头注释

1.修改unity生成CS文件的模板(模板位置:Unity\Editor\Data\Resources\ScriptTemplates 文件名:81-C# Script-NewBehaviourScript.cs) 本人将模板修改为如下图(红框内的内容) 备注:在"#"之间的为可替换的参数 2.修改模板可替换参数,在工程项目Asset文件夹在创建Editor文件 在文件夹下添加AddFileHeadComment.cs文件 内容如下 参数内容根据个人需求修改

CS 和 BS 的区别和优缺点

bs是浏览器(browser)和服务器(server) cs是静态客户端程序(client)和服务器(server) 区别在于,虽然同样是通过一个程序连接到服务器进行网络通讯,但是bs结构的,客户端运行在浏览器里,比如你看百度,就是通过浏览器.还有一些bs结构的应用,比如中国电信,以及一些电子商务平台.用bs结构的好处是,不必专门开发一个客户端界面,可用asp,php,jsp等比较快速开发web应用的程序开发. cs结构的,要做一个客户端.网络游戏基本上大多是cs结构,比如你玩传奇,要专门开个传

微软SQLHelper.cs类 中文版

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Xml; using System.Collections; namespace LiuYanBanT { public class SqlHelper

AssemblyInfo.cs文件详解

一.前言 .net工程的Properties文件夹下自动生成一个名为AssemblyInfo.cs的文件,一般情况下我们很少直接改动该文件.但我们实际上通过另一个形式操作该文件.那就是通过在鼠标右键点击项目的属性进入“应用程序”->“程序集信息”,然后修改信息. 二.作用 通过特性(Attribute)来设置程序集(dll文件)的常规信息,供查看或作为配置信息供程序内部使用. 三.详解 // 程序集标题 [assembly:AssemblyTitle("程序集标题")] // 程

全局程序集GlobalAssemblyInfo.cs进行版本控制(引)

原文出自:http://blog.csdn.net/oyi319/article/details/5753311 1.全局程序集GlobalAssemblyInfo.cs 我们编写的一个解决方案,通常会包含多个项目,而每个项目都有单独的程序集信息AssemblyInfo.cs.但是,你会发现一个问题,这些AssemblyInfo.cs当中有一部分在重复的,若能把它们提取出来放入一个单一文件中,修改AssemblyInfo中的诸如产品名.产品版本.版本等信息会变得轻松.那么,这个程序集信息文件,我

【141030】CS结构的VC++远程控制程序源代码

CS结构的VC++远程控制程序源代码,类似于pcAnywhere的程序,程序分为主服务端和主控端.主控端也就是客户端,由用户发送指令到服务端后来控制受控计算机.因为服务端是安装在受控机上的,其程序原理与著名的远程控制软件PcAnywhere非常相似,只是只完成了基本功能,有兴趣的可自己扩展程序吧. 客户端: 服务端: 完整源码下载地址:点击下载

《CS:APP》 chapter 6 The Memory Hierarchy笔记

The Memory Hierarchy 6.1 Storage Technologies The earliest IBM PCs didn't even have a hard disk. 让我惊奇的是早期的IBM直接没有硬盘... 6.1.1 Random-Access Memory Random-access memory(RAM) comes in two varieties- static anddynamic . Static RAM (SRAM) is faster and si

CS游戏2--三次杀人机会,警察不能杀人

#coding=utf-8 import randomimport time ''' 本文章主要目主要有三个,1,随机增加5个系统人物,所有的都是随机产生的,2,人物角色如果是警察,则不能杀死警察,3,有三次机会杀死敌方 涉及的知识点有,随机数的产生,字典的存储和遍历 ''' list_kill=[0,1,1,1]list_name=range(10)dir_weapen={"AK47":2000,"匕首":500,"小手枪":1000}dir_