gpt4 book ai didi

c# - HttpListener 如何提供图像

转载 作者:行者123 更新时间:2023-11-30 20:46:45 27 4
gpt4 key购买 nike

我正在制作一个简单的网络服务器来提供 html、css、js 和图像(在 c# 中完成)。我正在使用 HttpListener,我可以让 html、javascript 和 css 文件正常工作。我只是在处理图像时遇到问题。这是我目前使用的:

        if (request.RawUrl.ToLower().Contains(".png") || request.RawUrl.Contains(".ico") || request.RawUrl.ToLower().Contains(".jpg") || request.RawUrl.ToLower().Contains(".jpeg"))
{
string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string[] img = request.RawUrl.Split('/');
string path = dir + @"\public\imgs\" + img[img.Length - 1];

FileInfo fileInfo = new FileInfo(path);
long numBytes = fileInfo.Length;

FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
byte[] output = binaryReader.ReadBytes((int)numBytes);
binaryReader.Close();
fileStream.Close();

var temp = System.Text.Encoding.UTF8.GetString(output);
return temp;
}

我正在将图像转换为字符串以返回它们(这是我老板建议的方式)。这是我处理这些请求的方法。

private static string SendResponse(HttpListenerRequest request)

这是我的 WebServer 类的 Run() 方法。对 SetContentType 的调用只是通过 request.RawUrl 并确定内容类型。

public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
Console.WriteLine("StackLight Web Server is running...");

try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;

try
{
// store html content in a byte array
string responderString = _responderMethod(ctx.Request);

// set the content type
ctx.Response.Headers[HttpResponseHeader.ContentType] = SetContentType(ctx.Request.RawUrl);

byte[] buffer = buffer = Encoding.UTF8.GetBytes(responderString);


// this writes the html out from the byte array
ctx.Response.ContentLength64 = buffer.Length;
using(Stream stream = ctx.Response.OutputStream)
{
stream.Write(buffer, 0, buffer.Length);
}
}
catch (Exception ex)
{
ConfigLogger.Instance.LogCritical(LogCategory, ex);
}
}, _listener.GetContext());
}
}
catch (Exception ex)
{
ConfigLogger.Instance.LogCritical(LogCategory, ex);
}
});
}

我的 html 页面需要在屏幕上显示图像,到目前为止它显示的是一个损坏的图像。我知道图像目录是正确的,我测试过。

这是我获得网络服务器代码的地方:here

我在想也许我必须将 SendResponse 方法更改为不返回字符串

最佳答案

我想通了。我创建了一个类来保存数据、内容类型和 request.RawUrl。然后,在传递字符串的地方,我将其更改为传递我创建的对象。

因此,对于我的 WebServer 类,我的 Run 方法如下所示:

public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
Console.WriteLine("StackLight Web Server is running...");

try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;

try
{
// set the content type
ctx.Response.Headers[HttpResponseHeader.ContentType] = SetContentType(ctx.Request.RawUrl);
WebServerRequestData data = new WebServerRequestData();

// store html content in a byte array
data = _responderMethod(ctx.Request);

string res = "";
if(data.ContentType.Contains("text"))
{
char[] chars = new char[data.Content.Length/sizeof(char)];
System.Buffer.BlockCopy(data.Content, 0, chars, 0, data.Content.Length);
res = new string(chars);
data.Content = Encoding.UTF8.GetBytes(res);
}

// this writes the html out from the byte array
ctx.Response.ContentLength64 = data.Content.Length;
ctx.Response.OutputStream.Write(data.Content, 0, data.Content.Length);
}
catch (Exception ex)
{
ConfigLogger.Instance.LogCritical(LogCategory, ex);
}
finally
{
ctx.Response.OutputStream.Close();
}
}, _listener.GetContext());
}
}
catch (Exception ex)
{
ConfigLogger.Instance.LogCritical(LogCategory, ex);
}
});
}

我的 SendResponse 方法如下所示:

private static WebServerRequestData SendResponse(HttpListenerRequest request)
{
string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string[] fileUrl = request.RawUrl.Split('/');

// routes
if (request.RawUrl.Contains("/"))
{
// this is the main page ('/'), all other routes can be accessed from here (including css, js, & images)
if (request.RawUrl.ToLower().Contains(".png") || request.RawUrl.ToLower().Contains(".ico") || request.RawUrl.ToLower().Contains(".jpg") || request.RawUrl.ToLower().Contains(".jpeg"))
{
try
{
string path = dir + Properties.Settings.Default.ImagesPath + fileUrl[fileUrl.Length - 1];

FileInfo fileInfo = new FileInfo(path);
path = dir + @"\public\imgs\" + fileInfo.Name;

byte[] output = File.ReadAllBytes(path);

_data = new WebServerRequestData() {Content = output, ContentType = "image/png", RawUrl = request.RawUrl};
//var temp = System.Text.Encoding.UTF8.GetString(output);

//return Convert.ToBase64String(output);
return _data;
}
catch(Exception ex)
{
ConfigLogger.Instance.LogError(LogCategory, "File could not be read.");
ConfigLogger.Instance.LogCritical(LogCategory, ex);
_errorString = string.Format("<html><head><title>Test</title></head><body>There was an error processing your request:<br />{0}</body></html>", ex.Message);
_byteData = new byte[_errorString.Length * sizeof(char)];
System.Buffer.BlockCopy(_errorString.ToCharArray(), 0, _byteData, 0, _byteData.Length);

_data = new WebServerRequestData() { Content = _byteData, ContentType = "text/html", RawUrl = request.RawUrl };
return _data;
}
}

我仍在稍微清理一下代码,但它现在可以提供图片了!

哦...这是我正在使用的对象:

public class WebServerRequestData
{
public string RawUrl { get; set; }
public string ContentType { get; set; }
public byte[] Content { get; set; }
public string RawData { get; set; }
}

关于c# - HttpListener 如何提供图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26513743/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com