. net中文件下載

   //TransmitFile實現下載
    public void xiazai(string filePath, string yname)
    {

        /*
         微軟爲Response對象提供了一個新的方法TransmitFile來解決使用Response.BinaryWrite
         下載超過400MB的文件時導致Aspnet_wp.exe進程回收而無法成功下載的問題。
         代碼如下:
         */

        try
        {

            //Response.Write(this.FileUpload1.PostedFile.ContentLength);
            //Response.Write(this.FileUpload1.PostedFile.ContentType);
            //Response.Write(System.IO.Path.GetExtension(name)); //擴展名
            //Response.Write(System.IO.Path.GetFileName(fileName));//文件名
            //return;
            if (filePath == "" || !File.Exists(Server.MapPath(filePath)))
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('暫無該文件!')</script>");
                return;
            }

            string path = Server.MapPath(filePath);
            Response.ContentType = "application/x-*-compressed";
            //Response.ContentType = "application/x-zip-compressed";//保存類型

            //解決亂碼問題(在web.config配置文件中只配置responseEncoding='UTF-8'無效)
            yname = Server.UrlEncode(yname);
            // yname = HttpUtility.UrlEncode(yname);
            //yname = HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(yname));

            Response.AddHeader("Content-Disposition", "attachment;filename=" + yname);

            Response.TransmitFile(path);

 

            //  兩種解決亂碼方法  
            //  1.如果web.config裏utf-8   (gb2312不行)
            //  直接Server.UrlEncode(filename)就可以  

            //  2.否則就要用第二種方法  
            //  filename=HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(filename));

            //  好象編碼必須是 UTF8,不管您的

            // Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");

            //這個語句裏面寫的是什麼編碼.

 

        }
        catch
        {
            //打開時異常了
            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('暫無該文件')</script>");
            return;
        }

    }

 

 

//下載方法二
    public void xiazai()
    {

        string FullFileName = "";

        //ASP.NET下載文件(彈出打開保存文件對話框)
        //fileURL爲帶路徑的文件全名
        /*
         string fileURL = url;
         System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileURL);
         Response.Clear();
         Response.AddHeader("content-disposition","attachment;filename="+Server.UrlEncode(fileInfo.Name.ToString()));
         Response.AddHeader("content-length",fileInfo.Length.ToString());
         Response.ContentType = "application/octet-stream";
         Response.ContentEncoding = System.Text.Encoding.Default;
         Response.WriteFile(fileURL);
         */

        //無錯版:
        try
        {
            string FileName = "file/fenye.rar";
            //FileName = "分頁.rar";
            FullFileName = Server.MapPath(FileName);
            //FileName--要下載的文件名
            FileInfo DownloadFile = new FileInfo(FullFileName);
            if (DownloadFile.Exists)
            {
                Response.Clear();
                Response.ClearHeaders();
                Response.Buffer = false;
                Response.ContentType = "application/octet-stream";
                Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.ASCII));
                Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
                Response.WriteFile(DownloadFile.FullName);
                Response.Flush();
                Response.End();
            }
            else
            {
                //文件不存在
            }
        }
        catch
        {
            //打開時異常了
        }

    }

 

 

 

  //下載方法三:Response.BinaryWrite下載
    public static bool ResponseFile1(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath)
    {
        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;

                double pack = 10240; //10K bytes
                int sleep = 500;   //每秒5次   即5*10K bytes每秒,,改20K/秒   500毫秒
                //int sleep = (int)Math.Floor(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());
                _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((fileLength - startBytes) / pack) + 1;
                for (int i = 0; i < maxCount; i++)
                {
                    if (_Response.IsClientConnected)
                    {
                        _Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
                        //將一個2進制字符串寫入到HTTP輸出流,ReadBytes,從當前
                        Thread.Sleep(sleep);//2000是2秒,把CPU讓給別的進程
                    }
                    else
                    {
                        i = maxCount;
                    }
                }

            }
            catch
            {
                return false;
            }
            finally
            {
                br.Close();

                myFile.Close();
            }
        }
        catch
        {
            return false;
        }
        return true;
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章