服务器端:
1.新建一个Asp.net空网站RGImageServer。
2.新建一个WebService项目ImageService,项目新增文件ImageService.asmx,添加方法GetTile()。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Configuration; namespace RGImageServer
{
/// <summary>
/// ImageServices 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class ImageServices : System.Web.Services.WebService
{ [WebMethod]
public string HelloWorld()
{
return "Hello World";
}
private byte[] Stream2Bytes(Stream theStream)
{
int num;
MemoryStream stream = new MemoryStream();
while ((num = theStream.ReadByte()) != -1)
{
stream.WriteByte((byte)num);
}
theStream.Close();
return stream.ToArray();
}
[WebMethod]
public void GetTile(string imageName)
{
string filename = ConfigurationManager.AppSettings["ImagePath"] + @"\" + imageName;
HttpContext context = this.Context;
if (File.Exists(filename))
{
try
{
FileStream theStream = File.OpenRead(filename);
context.Response.ContentType = "image/png";
byte[] buffer = Stream2Bytes(theStream);
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
}
catch (Exception)
{
context.Response.StatusCode = 500;
}
}
}
}
}
3.配置WebConfig文件,发布服务。
<?xml version="1.0" encoding="utf-8"?> <!--
有关如何配置 ASP.NET 应用程序的详细消息,请访问
http://go.microsoft.com/fwlink/?LinkId=169433
--> <configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<webServices>
<protocols>
<add name="HttpGet" />
<add name="HttpPost" />
<add name="HttpSoap" />
</protocols>
</webServices>
</system.web>
<appSettings>
<add key="ImagePath" value="E:\"/>
</appSettings>
</configuration>
客户端:
1.调用下载图片代码如下:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Stream ContentStream;
HttpWebResponse response = null;
string ContentType;
string ContentEncoding;
int ContentLength = ;
int BytesProcessed;
private void button1_Click(object sender, EventArgs e)
{
ImageServices server = new ImageServices();
string Url = "http://localhost:6235/ImageServices.asmx/GetTile?imageName=aa.png";
string SavedFilePath = "D:\\bb.png";
// Download to file
string targetDirectory = Path.GetDirectoryName(SavedFilePath);
if (targetDirectory.Length > )
Directory.CreateDirectory(targetDirectory);
ContentStream = new FileStream(SavedFilePath, FileMode.Create);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.ContentType = "text/xml";
using (response = request.GetResponse() as HttpWebResponse)
{
// only if server responds 200 OK
if (response.StatusCode == HttpStatusCode.OK)
{
ContentType = response.ContentType;
ContentEncoding = response.ContentEncoding; // Find the data size from the headers.
string strContentLength = response.Headers["Content-Length"];
if (strContentLength != null)
{
ContentLength = int.Parse(strContentLength);
}
//缓存字节数组,大小1500byte
byte[] readBuffer = new byte[];
using (Stream responseStream = response.GetResponseStream())
{
while (true)
{
// Pass do.readBuffer to BeginRead.
int bytesRead = responseStream.Read(readBuffer, , readBuffer.Length);
if (bytesRead <= )
break;
ContentStream.Write(readBuffer, , bytesRead);
BytesProcessed += bytesRead;
}
}
ContentStream.Close();
ContentStream.Dispose();
ContentStream = null;
}
} }
}
以下是一个一般处理程序ImageHandler用于图片发布,添加ImageHandler.ashx:
using System;
using System.Web;
using System.Configuration;
using System.IO; namespace RGImageServer
{
/// <summary>
/// ImageHandler 的摘要说明
/// </summary>
public class ImageHandler : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World"); string imageName = "aa.png";
string filename = ConfigurationManager.AppSettings["ImagePath"] + @"\" + imageName;
if (File.Exists(filename))
{
try
{
FileStream theStream = File.OpenRead(filename);
context.Response.ContentType = "image/png";
byte[] buffer = StreamToBytes(theStream);
context.Response.OutputStream.Write(buffer, , buffer.Length);
}
catch (Exception)
{ }
}
}
private byte[] StreamToBytes(Stream theStream)
{
int num;
MemoryStream stream = new MemoryStream();
while ((num = theStream.ReadByte()) != -)
{
stream.WriteByte((byte)num);
}
theStream.Close();
return stream.ToArray();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
ImageHandler
通过浏览器可以直接访问:http://localhost:6235/ImageHandler.ashx