图片下载原理:
(1)用 <a> 指向一个图片,然后在新窗口中打开,默认情况,只是在新窗口中打开图片,实现不了下载,要实现下载,必须用 aspx 页面,重写。
代码如下:
private void GetMapByWMS()
{
try
{
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("9999.jpg", System.Text.Encoding.UTF8));
string strUrl = "";
if (Request.Params["img"] != null)
{
strUrl = Request.Params["img"].ToString();
}
else
{
Response.Write("参数出错,请不要直接访问本文站!");
Response.End();
return;
}
HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(strUrl);
HttpWReq.Method = "Get";
HttpWReq.ContentLength = 0;
HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
Stream strm = HttpWResp.GetResponseStream();
int count1 = (int)HttpWResp.ContentLength;
if (count1 == -1)
{
count1 = 1024 * 1024 * 5;
}
byte[] buffer = new byte[count1];
int c = 0;
int k = strm.Read(buffer, 0, count1);
c = c + k;
// 读几次,直到读完
while (k != 0)
{
k = strm.Read(buffer, c, count1 - c);
c = c + k;
}
strm.Close();
Response.OutputStream.Write(buffer, 0, buffer.Length);
}
catch (Exception ee)
{
Response.Write(ee.Message);
}
}
(2) 用 <a> 指向这 页面,就会下载。
(3)如何用按钮触发下载。用 iframe, 用 js 代码将 ifarme 指向上面那个页面,就会实现单击按钮下载图片。