c# - 如何将图像发送到浏览器

标签 c# asp.net

我正在构建一个简化的网络服务器,我能够正确地处理发送 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

我假设 sw 是一个 StreamWriter,但您需要写入图像的 raw 字节。

那么怎么样:

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 这样的工具真的很有帮助查看浏览器和(真实的)网络服务器之间的通信并尝试复制它。

关于c# - 如何将图像发送到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7077035/

相关文章:

c# - 有很多渲染部分功能不好吗?

c# - 如何在不重新加载页面的情况下刷新下拉列表?

c# - 为什么XmlSerializer可以序列化抽象类而不能序列化接口(interface)?

c# - LoadControl,WebMethod 中的用户控件

asp.net - 3 层架构中的数据绑定(bind)?

c# - 如何从代码隐藏中找到跨度并向其添加用户控件?

c# - 如何将 DataGridView 定位到特定行(以便所选行位于底部)?

c# - 可以在一个对象上多次调用Dispose()导致崩溃吗?

c# - Server.MapPath VS。 @Href ("~/SomeFile.cshtml")

javascript - Facebox 弹出窗口 + asp.net 按钮回发问题