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

      

  • 相关阅读:
    Wrong codepoints for non-ASCII characters inserted in UTF-8 database using CLP
    SqlException with message "Caught java.io.CharConversionException." and ERRORCODE=-4220
    XSD 数据类型
    Can't read [proguard.ClassPathEntry@1a0c10f] (No such file or directory)
    ubuntu 创建swap分区
    tar分层压缩
    MTK 自定义系统服务
    MTK framework系统默认设置
    MTK 修改默认屏幕亮度
    MTK 隐藏底部状态栏
  • 原文地址:https://www.cnblogs.com/dennysong/p/5609032.html
Copyright © 2020-2023  润新知