日期:2014-05-16 浏览次数:20462 次
#region 下载文件处理-downfiledeal /// <summary> /// 下载文件处理 /// </summary> /// <param name="ResourceID">资源id</param> /// <param name="UserID">用户id</param> /// <param name="downtype">下载类型:1-购买,2-今日免费,3-订阅用户</param> /// <param name="webtitle">提示页面titie</param> /// <param name="ResourceType">资源类型(暂时不考虑)</param> /// <returns></returns> private string downfiledeal(string ResourceID, string UserID, string downtype, string webtitle, string ResourceType = "") { TopicInformationBLL bll_tf = new TopicInformationBLL(); TopicInformation tf = bll_tf.GetById(ResourceID); bll_tf.Dispose(); string FilePath = ""; FilePath = tf.TopicSourceFile.ToLower(); if (FilePath.StartsWith("http://www.***.com"))//不是外网文件夹服务器路径 { FilePath = FilePath.Replace("http://www.***.com", ""); } if (!FilePath.StartsWith("/")) FilePath = "/" + FilePath; FilePath = Server.MapPath(FilePath); FileInfo DownloadFile = new FileInfo(FilePath); System.IO.Stream iStream = null; int downsize = 1024;//读取web.config中的配置 try { downsize = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["downsize"]); } catch { downsize = 1024; } int buffersize = 1024 * downsize;//默认每次发送1K; byte[] buffer = new Byte[buffersize];// Buffer to read 10K bytes in chunk: int currentlength;// Length of each read to buffer: long dataToRead;// Total bytes to read: long dataSended;//已发送的字节 long datalength;//文件字节总长度 string filename = System.IO.Path.GetFileName(FilePath); // Identify the file name. try { System.Collections.Specialized.NameValueCollection hds = Request.Headers; long startBytes = 0; Response.Clear(); Response.ClearHeaders(); if (Request.Headers["Range"] != null) {//------如果是续传请求,则获取续传的起始位置,即已经下载到客户端的字节数------ Response.StatusCode = 206;//重要:续传必须,表示局部范围响应。初始下载时默认为200 string[] range = Request.Headers["Range"].Split(new char[] { '=', '-' });//"bytes=1474560-" startBytes = Convert.ToInt64(range[1]);//已经下载的字节数,即本次下载的开始位置 if (startBytes < 0 || startBytes >= DownloadFile.Length) {//无效的起始位置 startBytes = 0; } } iStream = new System.IO.FileStream(FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);// Open the file. dataSended = 0; datalength = dataToRead = iStream.Length - startBytes;// Total bytes to read: Response.Buffer = true; string lastUpdateTiemStr = System.IO.File.GetLastWriteTimeUtc(FilePath).ToString("r"); string eTag = HttpUtility.UrlEncode(filename, Encoding.UTF8) + lastUpdateTiemStr; Response.AppendHeader("ETag", "\"" + eTag + "\"");//重要:续传必须 if (startBytes > 0) { if (Request.Headers["If-Range"] != null)//(IE,360)对应响应头ETag:文件名+文件最后修改时间 { //----------上次被请求的日期之后被修改过-------------- string If_Range = Request.Headers["If-Range"].Replace("\&quo