zoukankan      html  css  js  c++  java
  • 点击下载按钮下载文件到本地 download stream to local

     protected void Down_Load(object sender, EventArgs e)
     {
            //create a stream for the file
            Stream stream = null;
            //this controls how many bytes to read at a time and send to the client
            int bytesToRead = 10000;
            //buffer to read bytes in chunk size specified above 
            byte[] buffer = new byte[bytesToRead];
            string url = "http://stv1.222.net/mv/dkp10608.mp4";
            string fileName = "11.mp4";
            try
            {
                //create a webrequest to get the file
                HttpWebRequest fileReq = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
                if (fileReq.ContentLength > 0)
                    fileResp.ContentLength = fileReq.ContentLength;
                stream = fileResp.GetResponseStream();
                var resp = HttpContext.Current.Response;
                resp.ContentType = "application/octet-stream";
                //indicate the type of data being sent
                resp.AddHeader("Content-Disposition", "attachment;filename="" + fileName + """);
                resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
    
                int length;
                do
                {
                    //verify that client is connected
                    if (resp.IsClientConnected)
                    {
                        //read data into the buffer
                        length = stream.Read(buffer, 0, bytesToRead);
                        //and write it out to the response's output stream
                        resp.OutputStream.Write(buffer, 0, length);
                        //flush the data
                        resp.Flush();
                        //clear the data
                        buffer = new byte[bytesToRead];
                    }
                    else
                    {
                        //cancel the download if client has disconnected
                        length = -1;
                    }
                } while (length > 0); //repeat until no data is read
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (stream != null)
                {
                    //close the input stream
                    stream.Close();
                }
            }
    }
    

      

  • 相关阅读:
    开场白
    八皇后(DFS)
    function-paren-newline (Rules) – Eslint 中文开发手册
    Java面试题:Error和Exception有什么区别?
    Linux mmove 命令
    字母间距 | letter-spacing (Scalable Vector Graphics) – CSS 中文开发手册
    object.watch (Object) – JavaScript 中文开发手册
    ASP.NET MVC HTML 帮助器
    C 库函数 – strerror()
    Java中的初始化模块
  • 原文地址:https://www.cnblogs.com/dennysong/p/5609032.html
Copyright © 2011-2022 走看看