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

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

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

 

下面这个方法实现的是把图片读取为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();
}
复制代码
posted @ 2019-12-13 18:57  豆豆子灬灬  阅读(288)  评论(0编辑  收藏  举报