gpt4 book ai didi

c# - 在 C# 中使用 HTTP 发送 PNG

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:23:53 24 4
gpt4 key购买 nike

我正在用 C# 开发我自己的简单网络服务器,我有正常的 html 文件和子文件夹等,并且工作正常......但是我的问题在于发送 PNG 文件。

一旦浏览器发出了 HTTP 请求并且我的其他代码发挥了它的魔力,我就需要发送一个响应 header 。这是我执行此操作的代码:

        else if (URL.EndsWith(".ico") || URL.EndsWith(".png"))
{
if (File.Exists(Program.Start_Directory + URL))
{
byte[] ImgFile = File.ReadAllBytes(Program.Start_Directory + URL);
sw.Write("HTTP/1.0 200 OK\r\n");
sw.Write("Content-Type: image/png\r\n");
sw.Write("Content-Length: " + ImgFile.Length + "\r\n");
sw.Write("\r\n");
sw.Write(ImgFile);
}
else
{
FileNotFoundPage(sw);
}
}

在此实例中,sw 是用于到浏览器的套接字连接的 StreamWriter。

当我运行它时,浏览器屏幕变黑,就像它通常在加载图像时一样,但没有图像加载并且旋转的加载轮无限期地保持旋转。

我怎样才能让它发挥作用?谢谢。

最佳答案

当您使用带有二进制数据的 StreamWriter(设计用于将具有特定 Encoding 的字符串写入流)时,事情会变得一团糟。

看起来你正在调用 this StreamWriter.Write 的重载,相信它会将字节逐字写入输出流。文档指出这种过载实际上......

Writes the text representation of an object to the text string or stream by calling the ToString method on that object

您有两个选择。继续使用StreamWriterFlush,然后将二进制数据直接写入底层流:

byte[] ImgFile = File.ReadAllBytes(Program.Start_Directory + URL);
sw.Write("HTTP/1.0 200 OK\r\n");
//...etc
sw.Flush();
sw.BaseStream.Write(ImgFile,0,ImgFile.Length);

或者只是以字节为单位做所有事情:

var sb=new StringBuilder();
sb.AppendLine("HTTP/1.0 200 OK");
//...etc
var headerBytes = Encoding.ASCII.GetBytes(sb.ToString());
Stream str = iGotTheStreamFromSomewhere;
str.Write(headerBytes,0,headerBytes.Length);
str.Write(ImgFile,0,ImgFile.Length);

关于c# - 在 C# 中使用 HTTP 发送 PNG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47756901/

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