天天看点

服务器上的图片下载

  string filepath = ipt.Value;//jpg http url路径

            #region 下载代码

            System.IO.Stream iStream = null;

            int length = 0;// Length of the file:

            long dataToRead;// Total bytes to read:

            string filename = filepath.Substring(filepath.LastIndexOf(@"/")+1, filepath.Length - filepath.LastIndexOf(@"/")-1); // 下载文件名

            try

            {

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filepath);

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                byte[] buffer = new byte[4096000];

                Response.ContentType = "application/octet-stream";

                Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename));

                dataToRead = response.ContentLength;

                while (dataToRead > 0)

                {

                    length = response.GetResponseStream().Read(buffer, 0, 4096000);

                    Response.OutputStream.Write(buffer, 0, length);

                    Response.Flush();

                    dataToRead = dataToRead - length;

                }

            }

            catch (Exception ex)

            {

                Response.Write("Error : " + ex.Message);// Trap the error, if any.

            }

            finally

            {

                if (iStream != null)

                    iStream.Close();//Close the file.

            }

            #endregion