如何发送图像到浏览器

本文关键字:浏览器 图像 何发送 | 更新日期: 2023-09-27 18:05:37

我正在构建一个简化的web服务器,我能够正确处理发送HTML页面

但是当我收到图像请求时,我的代码没有给浏览器图像

FileStream fstream = new FileStream(tempSplitArray[1],FileMode.Open,FileAccess.Read);
//The tempSplitArray //recieves the request from the browser
byte[] ar = new byte[(long)fstream.Length];
for (int i = 0; i < ar.Length; i++)
{
    ar[i] = (byte)fstream.ReadByte();
}
string byteLine = "Content-Type: image/JPEG'n" + BitConverter.ToString(ar);
sw.WriteLine(byteLine);//This is the network stream writer
sw.Flush();
fstream.Close();

请原谅我的无知,如果有任何问题,或者我的问题不够清楚,请告诉我。

如何发送图像到浏览器

基本上你希望你的回复看起来像:

HTTP/1.1 200 OK
Content-Type: image/jpeg
Content-Length: *length of image*
Binary Image Data goes here

我假设swStreamWriter,但您需要写入图像的原始字节。

那么:

byte[] ar;
using(FileStream fstream = new FileStream(tempSplitArray[1],FileMode.Open,FileAccess.Read);)
{
    //The tempSplitArray //recieves the request from the browser
    ar = new byte[(long)fstream.Length];
    fstream.read(ar, 0, fstream.Length);
}
sw.WriteLine("Content-Type: image/jpeg");
sw.WriteLine("Content-Length: {0}", ar.Length); //Let's 
sw.WriteLine(); 
sw.BaseStream.Write(ar, 0, ar.Length);

使用fiddler这样的工具来查看浏览器和(真正的)web服务器之间的通信,并尝试复制它真的很有帮助。