写一个 C#监听HTTPPOST发送过来的图片文件 并存在D盘的test文件夹里
时间: 2024-02-17 09:01:47 浏览: 104
好的,以下是监听HTTP POST请求并保存图片文件的C#示例代码:
```csharp
using System;
using System.IO;
using System.Net;
using System.Text;
namespace HttpListenerExample
{
class Program
{
static void Main(string[] args)
{
// 创建HttpListener对象
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/"); // 监听的URL
listener.Start();
Console.WriteLine("HttpListener is running...");
while (true)
{
// 等待请求
HttpListenerContext context = listener.GetContext();
// 获取请求的HTTP方法类型和路径
string httpMethod = context.Request.HttpMethod;
string requestPath = context.Request.Url.AbsolutePath;
// 仅处理POST请求
if (httpMethod == "POST")
{
// 读取POST请求的数据
StreamReader reader = new StreamReader(context.Request.InputStream);
string requestBody = reader.ReadToEnd();
// 解析POST请求的数据,获取文件名和文件内容
string[] parts = requestBody.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
string fileName = "";
byte[] fileContent = new byte[0];
foreach (string part in parts)
{
if (part.StartsWith("Content-Disposition: form-data; name=\"file\"; filename=\""))
{
fileName = part.Substring(part.IndexOf("filename=\"") + 10).Replace("\"", "");
}
else if (part.StartsWith("Content-Type:"))
{
// 跳过Content-Type行
}
else
{
// 读取文件内容
fileContent = Encoding.UTF8.GetBytes(part);
}
}
// 将文件内容保存到本地文件
string filePath = "D:\\test\\" + fileName;
File.WriteAllBytes(filePath, fileContent);
// 发送响应
string responseString = "File saved to " + filePath;
byte[] responseBytes = Encoding.UTF8.GetBytes(responseString);
context.Response.ContentLength64 = responseBytes.Length;
context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length);
context.Response.OutputStream.Close();
}
else
{
// 发送404错误响应
context.Response.StatusCode = 404;
context.Response.Close();
}
}
}
}
}
```
注意:该示例代码仅用于演示如何监听HTTP POST请求并保存文件,实际应用中应该加入错误处理、安全验证等功能。
阅读全文