Html代碼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#通常處理程序代碼web
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; } } } }