电竞比分网-中国电竞赛事及体育赛事平台

分享

asp.net mvc如何實現(xiàn)文件下載

 仰望//45度微笑 2012-05-29
public static bool DownloadFile(HttpContext httpContext, string filePath, long speed)  
{  
    bool ret = true;  
    try 
    {  
      #region--驗證:HttpMethod,請求的文件是否存在  
        switch (httpContext.Request.HttpMethod.ToUpper())  
        { //目前只支持GET和HEAD方法  
            case "GET":  
            case "HEAD":  
                break;  
            default:  
                httpContext.Response.StatusCode = 501;  
                return false;  
        }  
        if (!File.Exists(filePath))  
        {  
            httpContext.Response.StatusCode = 404;  
            return false;  
        }  
        #endregion  
 
       #region 定義局部變量  
         long startBytes = 0;  
        int packSize = 1024 * 10; //分塊讀取,每塊10K bytes  
        string fileName = Path.GetFileName(filePath);  
        FileStream myFile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);  
        BinaryReader br = new BinaryReader(myFile);  
        long fileLength = myFile.Length;  
 
        int sleep = (int)Math.Ceiling(1000.0 * packSize / speed);//毫秒數(shù):讀取下一數(shù)據(jù)塊的時間間隔  
        string lastUpdateTiemStr = File.GetLastWriteTimeUtc(filePath).ToString("r");  
        string eTag = HttpUtility.UrlEncode(fileName, Encoding.UTF8) + lastUpdateTiemStr;//便于恢復(fù)下載時提取請求頭;  
        #endregion  
 
        #region--驗證:文件是否太大,是否是續(xù)傳,且在上次被請求的日期之后是否被修  
        if (myFile.Length > Int32.MaxValue)  
        {//-------文件太大了-------  
            httpContext.Response.StatusCode = 413;//請求實體太大  
            return false;  
        }  
 
        if (httpContext.Request.Headers["If-Range"] != null)//對應(yīng)響應(yīng)頭ETag:文件名+文件最后修改時間  
        {  
            //----------上次被請求的日期之后被修改過--------------  
            if (httpContext.Request.Headers["If-Range"].Replace("\"", "") != eTag)  
            {//文件修改過  
                httpContext.Response.StatusCode = 412;//預(yù)處理失敗  
                return false;  
            }  
        }  
        #endregion  
 
        try 
        {  
         #region -------添加重要響應(yīng)頭、解析請求頭、相關(guān)驗證-------------------  
            httpContext.Response.Clear();  
            httpContext.Response.Buffer = false;  
            httpContext.Response.AddHeader("Content-MD5", GetMD5Hash(myFile));//用于驗證文件  
            httpContext.Response.AddHeader("Accept-Ranges", "bytes");//重要:續(xù)傳必須  
            httpContext.Response.AppendHeader("ETag", "\"" + eTag + "\"");//重要:續(xù)傳必須  
            httpContext.Response.AppendHeader("Last-Modified", lastUpdateTiemStr);//把最后修改日期寫入響應(yīng)                  
            httpContext.Response.ContentType = "application/octet-stream";//MIME類型:匹配任意文件類型  
            httpContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).Replace("+", "%20"));  
            httpContext.Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());  
            httpContext.Response.AddHeader("Connection", "Keep-Alive");  
            httpContext.Response.ContentEncoding = Encoding.UTF8;  
            if (httpContext.Request.Headers["Range"] != null)  
            {//------如果是續(xù)傳請求,則獲取續(xù)傳的起始位置,即已經(jīng)下載到客戶端的字節(jié)數(shù)------  
                httpContext.Response.StatusCode = 206;//重要:續(xù)傳必須,表示局部范圍響應(yīng)。初始下載時默認(rèn)為200  
                string[] range = httpContext.Request.Headers["Range"].Split(new char[] { '=', '-' });//"bytes=1474560-"  
                startBytes = Convert.ToInt64(range[1]);//已經(jīng)下載的字節(jié)數(shù),即本次下載的開始位置    
                if (startBytes < 0 || startBytes >= fileLength)  
                {//無效的起始位置  
                    return false;  
                }  
            }  
            if (startBytes > 0)  
            {//------如果是續(xù)傳請求,告訴客戶端本次的開始字節(jié)數(shù),總長度,以便客戶端將續(xù)傳數(shù)據(jù)追加到startBytes位置后----------  
                httpContext.Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));  
            }  
            #endregion  
 
            #region -------向客戶端發(fā)送數(shù)據(jù)塊-------------------  
            br.BaseStream.Seek(startBytes, SeekOrigin.Begin);  
            int maxCount = (int)Math.Ceiling((fileLength - startBytes + 0.0) / packSize);//分塊下載,剩余部分可分成的塊數(shù)  
            for (int i = 0; i < maxCount && httpContext.Response.IsClientConnected; i++)  
            {//客戶端中斷連接,則暫停  
                httpContext.Response.BinaryWrite(br.ReadBytes(packSize));  
                httpContext.Response.Flush();  
                if (sleep > 1) Thread.Sleep(sleep);  
            }  
            #endregion  
        }  
        catch 
        {  
            ret = false;  
        }  
        finally 
        {  
            br.Close();  
            myFile.Close();  
        }  
    }  
    catch 
    {  
        ret = false;  
    }  
    return ret;  
}

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多