C#下载图片,用户选择保存路径
Html代码
1 <html xmlns="http://www.w3.org/1999/xhtml"> 2 <head> 3 <title></title> 4 </head> 5 <body> 6 <a href="ImgDownloadHandler.ashx">下载</a> 7 <img src="http://10.1.18.59/CenterPointService/RainfallCenterTemp/20180319155952/20170601__20170930.png" 8 alt="RainfallCenter" id="RainfallCenter" /> 9 </body> 10 </html>
C#一般处理程序代码
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI.MobileControls; using System.Drawing; using System.IO; using System.Net; namespace WebApplication1 { /// <summary> /// ImgDownloadHandler 的摘要说明 /// </summary> public class ImgDownloadHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { #region action 2 可以导出图片 Stream stream = null; string UrlImg = "http://10.1.18.59/CenterPointService/RainfallCenterTemp/20180319155952/20170601__20170930.png"; WebClient webClient = new WebClient(); webClient.Credentials = CredentialCache.DefaultCredentials; //以数组的形式下载指定文件 byte[] byteData = webClient.DownloadData(UrlImg); stream = BytesToStream(byteData); string fileName = "20170601__20170930.png";//客户端保存的文件名 context.Response.ContentType = "application/octet-stream"; //通知浏览器下载文件而不是打开 context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); context.Response.BinaryWrite(byteData); context.Response.Flush(); context.Response.End(); #endregion } /// <summary> /// 将二进制转化为数据流 /// </summary> /// <param name="bytes">二进制数组</param> /// <returns></returns> public Stream BytesToStream(byte[] bytes) { Stream stream = new MemoryStream(bytes); return stream; } /// <summary> /// 将流转化为二进制数组 /// </summary> /// <param name="stream"></param> /// <returns></returns> public byte[] StreamToBytes(Stream stream) { byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); return bytes; } public bool IsReusable { get { return false; } } } }