• 点击下载按钮下载文件到本地 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();
                }
            }
    }
    

      

  • 相关阅读:
    【Codeforces542E】Playing on Graph [Bfs][Dfs]
    【Codeforces441E】Valera and Number [DP]
    单链表快速排序
    一个简易内存池(C++)
    最长回文子串---Manacher算法
    hihocoder 1015题
    简单的字典树(前缀树)
    C++获取基类指针所指子类对象的类名
    Muduo阅读笔记---net(三)
    C++线程安全的单例模式
  • 原文地址:https://www.cnblogs.com/dennysong/p/5609032.html
Copyright © 2020-2023  润新知