C#图片下载

        #region
        private byte[] GetImageContent(string picName)
        {
            string fileURL = "http://localhost:/img/" + picName;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileURL);
            request.AllowAutoRedirect = true;
            WebProxy proxy = new WebProxy();
            proxy.BypassProxyOnLocal = true;
            proxy.UseDefaultCredentials = true;
            request.Proxy = proxy;
            WebResponse response = request.GetResponse();
            using (Stream stream = response.GetResponseStream())
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    Byte[] buffer = new Byte[1024];
                    int current = 0;
                    while ((current = stream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        ms.Write(buffer, 0, current);
                    }
                    return ms.ToArray();
                }
            }
        }
        private void WriteResponse(string picName, byte[] content)
        {
            Response.Clear();
            Response.ClearHeaders();
            Response.Buffer = false;
            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(picName, Encoding.Default));
            Response.AppendHeader("Content-Length", content.Length.ToString());
            Response.BinaryWrite(content);
            Response.Flush();
            Response.End();
        }
        #endregion

        protected void btt_Click(object sender, EventArgs e)
        {
            byte[] content = this.GetImageContent("Desert.jpg");
            this.WriteResponse("Desert.jpg", content);
        }

 

posted @ 2013-01-14 13:53  Star★  阅读(330)  评论(0编辑  收藏  举报