码迷,mamicode.com
首页 > Web开发 > 详细

.net 已知图片的网络路径,通过浏览器下载图片

时间:2016-04-20 17:58:06      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

没什么技术含量,主要留给自己查找方便;

如题,知道图片的完整网络路径的情况下,在浏览器中下载图片的实现:

 

下面这个方法实现的是把图片读取为byte数组:

private byte[] GetImageContent(string url)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    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();
        }
    }
}

下面这方法是下载图片:

第一个参数:图片下载显示的文件名

第二个参数:通过上一个方法得到的byte数组,传进这里就可以了

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();
}

 

.net 已知图片的网络路径,通过浏览器下载图片

标签:

原文地址:http://www.cnblogs.com/zzgblog/p/5413593.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!