利用WebService发布图片文件
服务器端:
1.新建一个Asp.net空网站RGImageServer。
2.新建一个WebService项目ImageService,项目新增文件ImageService.asmx,添加方法GetTile()。

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.Services;
6 using System.IO;
7 using System.Configuration;
8
9 namespace RGImageServer
10 {
11 /// <summary>
12 /// ImageServices 的摘要说明
13 /// </summary>
14 [WebService(Namespace = "http://tempuri.org/")]
15 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
16 [System.ComponentModel.ToolboxItem(false)]
17 // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
18 // [System.Web.Script.Services.ScriptService]
19 public class ImageServices : System.Web.Services.WebService
20 {
21
22 [WebMethod]
23 public string HelloWorld()
24 {
25 return "Hello World";
26 }
27 private byte[] Stream2Bytes(Stream theStream)
28 {
29 int num;
30 MemoryStream stream = new MemoryStream();
31 while ((num = theStream.ReadByte()) != -1)
32 {
33 stream.WriteByte((byte)num);
34 }
35 theStream.Close();
36 return stream.ToArray();
37 }
38 [WebMethod]
39 public void GetTile(string imageName)
40 {
41 string filename = ConfigurationManager.AppSettings["ImagePath"] + @"\" + imageName;
42 HttpContext context = this.Context;
43 if (File.Exists(filename))
44 {
45 try
46 {
47 FileStream theStream = File.OpenRead(filename);
48 context.Response.ContentType = "image/png";
49 byte[] buffer = Stream2Bytes(theStream);
50 context.Response.OutputStream.Write(buffer, 0, buffer.Length);
51 }
52 catch (Exception)
53 {
54 context.Response.StatusCode = 500;
55 }
56 }
57 }
58 }
59 }
3.配置WebConfig文件,发布服务。

1 <?xml version="1.0" encoding="utf-8"?>
2
3 <!--
4 有关如何配置 ASP.NET 应用程序的详细消息,请访问
5 http://go.microsoft.com/fwlink/?LinkId=169433
6 -->
7
8 <configuration>
9 <system.web>
10 <compilation debug="true" targetFramework="4.0" />
11 <webServices>
12 <protocols>
13 <add name="HttpGet" />
14 <add name="HttpPost" />
15 <add name="HttpSoap" />
16 </protocols>
17 </webServices>
18 </system.web>
19 <appSettings>
20 <add key="ImagePath" value="E:\"/>
21 </appSettings>
22 </configuration>
客户端:
1.调用下载图片代码如下:

1 public partial class Form1 : Form
2 {
3 public Form1()
4 {
5 InitializeComponent();
6 }
7 Stream ContentStream;
8 HttpWebResponse response = null;
9 string ContentType;
10 string ContentEncoding;
11 int ContentLength = 0;
12 int BytesProcessed;
13 private void button1_Click(object sender, EventArgs e)
14 {
15 ImageServices server = new ImageServices();
16 string Url = "http://localhost:6235/ImageServices.asmx/GetTile?imageName=aa.png";
17 string SavedFilePath = "D:\\bb.png";
18 // Download to file
19 string targetDirectory = Path.GetDirectoryName(SavedFilePath);
20 if (targetDirectory.Length > 0)
21 Directory.CreateDirectory(targetDirectory);
22 ContentStream = new FileStream(SavedFilePath, FileMode.Create);
23 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
24 request.ContentType = "text/xml";
25 using (response = request.GetResponse() as HttpWebResponse)
26 {
27 // only if server responds 200 OK
28 if (response.StatusCode == HttpStatusCode.OK)
29 {
30 ContentType = response.ContentType;
31 ContentEncoding = response.ContentEncoding;
32
33 // Find the data size from the headers.
34 string strContentLength = response.Headers["Content-Length"];
35 if (strContentLength != null)
36 {
37 ContentLength = int.Parse(strContentLength);
38 }
39 //缓存字节数组,大小1500byte
40 byte[] readBuffer = new byte[1500];
41 using (Stream responseStream = response.GetResponseStream())
42 {
43 while (true)
44 {
45 // Pass do.readBuffer to BeginRead.
46 int bytesRead = responseStream.Read(readBuffer, 0, readBuffer.Length);
47 if (bytesRead <= 0)
48 break;
49 ContentStream.Write(readBuffer, 0, bytesRead);
50 BytesProcessed += bytesRead;
51 }
52 }
53 ContentStream.Close();
54 ContentStream.Dispose();
55 ContentStream = null;
56 }
57 }
58
59
60 }
61 }
以下是一个一般处理程序ImageHandler用于图片发布,添加ImageHandler.ashx:

1 using System;
2 using System.Web;
3 using System.Configuration;
4 using System.IO;
5
6 namespace RGImageServer
7 {
8 /// <summary>
9 /// ImageHandler 的摘要说明
10 /// </summary>
11 public class ImageHandler : IHttpHandler
12 {
13
14 public void ProcessRequest(HttpContext context)
15 {
16 //context.Response.ContentType = "text/plain";
17 //context.Response.Write("Hello World");
18
19 string imageName = "aa.png";
20 string filename = ConfigurationManager.AppSettings["ImagePath"] + @"\" + imageName;
21 if (File.Exists(filename))
22 {
23 try
24 {
25 FileStream theStream = File.OpenRead(filename);
26 context.Response.ContentType = "image/png";
27 byte[] buffer = StreamToBytes(theStream);
28 context.Response.OutputStream.Write(buffer, 0, buffer.Length);
29 }
30 catch (Exception)
31 {
32
33 }
34 }
35 }
36 private byte[] StreamToBytes(Stream theStream)
37 {
38 int num;
39 MemoryStream stream = new MemoryStream();
40 while ((num = theStream.ReadByte()) != -1)
41 {
42 stream.WriteByte((byte)num);
43 }
44 theStream.Close();
45 return stream.ToArray();
46 }
47 public bool IsReusable
48 {
49 get
50 {
51 return false;
52 }
53 }
54 }
55 }
通过浏览器可以直接访问:http://localhost:6235/ImageHandler.ashx
作者:太一吾鱼水
文章未经说明均属原创,学习笔记可能有大段的引用,一般会注明参考文献。
欢迎大家留言交流,转载请注明出处。
分类:
网络GIS
, 编程开发集合 / C#开发
标签:
WebService
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程