服务器端根据url文件下载后再转存到客户端

 Stream stream = null;
            //一次读取并返回到客户端的字节数
            var bytesToRead = 10000;
            //缓存上面读取到的字节
            var buffer = new Byte[bytesToRead];
            try
            {
                //创建WebRequest
                var fileReq = (HttpWebRequest)HttpWebRequest.Create(url);
                //为请求声明一个response
                var fileResp = (HttpWebResponse)fileReq.GetResponse();
                if (fileReq.ContentLength > 0)
                    fileResp.ContentLength = fileReq.ContentLength;
                //从请求响应中获取返回的Stream
                stream = fileResp.GetResponseStream();
                //准备当前客户端的响应
                var resp = HttpContext.Current.Response;
                //指定响应头的类型
                resp.ContentType = "application/octet-stream";
                //指定返回文件的名称
                resp.AddHeader("Content-Disposition", "attachment; filename=\"qq.exe\"");
                //指定返回文件的大小
                resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
                int length;
                do
                {
                    //检测当前客户端是否仍然和服务器保持连接状态
                    if (resp.IsClientConnected)
                    {
                        //读取数据到缓冲区
                        length = stream.Read(buffer, 0, bytesToRead);
                        resp.OutputStream.Write(buffer, 0, length);
                        resp.Flush();
                        //清空缓冲区
                        buffer = new Byte[bytesToRead];
                    }
                    else
                    {
                        //如果客户端和服务器和连接已丢失,则放弃下载
                        length = -1;
                    }
                } while (length > 0); //循环,直到stream的结束
            }
            finally
            {
                if (stream != null)
                {
                    //关闭stream
                    stream.Close();
                }
            }

 

posted @ 2023-10-09 16:22  麦田HH  阅读(40)  评论(0编辑  收藏  举报