我有下面的SimpleHttp服务器代码:
using (Stream fs = File.Open(@"C:UsersMohamedDesktopHany.jpg", FileMode.Open))
{
StreamWriter OutputStream = new StreamWriter(new BufferedStream(someSocket.GetStream()));
OutputStream.WriteLine("HTTP/1.0 200 OK");
OutputStream.WriteLine("Content-Type: application/octet-stream");
OutputStream.WriteLine("Content-Disposition: attachment; filename=Hany.jpg");
OutputStream.WriteLine("Content-Length: " + img.Length);
OutputStream.WriteLine("Connection: close");
OutputStream.WriteLine(""); // this terminates the HTTP headers
fs.CopyTo(OutputStream.BaseStream);
OutputStream.Flush();
//OutputStream.BaseStream.Flush();
}
问题是,当我看到输出http响应时,标头在文本的末尾,BaseStream中的图像二进制文件甚至在标头之前就出现在第一位。输出的示例是(当然我删除了图像的长字节):
ä3ST)ëî!ðDFYLQ>qâ:oÂÀó?ÿÙHTTP/1.0 200 OK
Content-Type: image/png
Connection: close
我想要的是颠倒顺序,把标题放在上面,得到的是这样的东西:
HTTP/1.0 200 OK
Content-Type: image/png
Connection: close
ä3ST)ëî!ðDFYLQ>qâ:oÂÀó?ÿÙT4ñ®KÛ'`ÃGKsCGÔ«¾+L»ê±?0Íse3rïÁå·>"ܼ;®N¦Ãõ5¨LZµL¯
在流写入程序或BaseStream上使用flush并不重要。任何帮助!
我认为问题是由对CopyTo的调用和传递BaseStream引起的。它可能会绕过尚未刷新数据的StreamWriter。
BaseStream不应用于写入。必须使用StreamWriter。
using (StreamWriter outputStream = new StreamWriter(new BufferedStream(someSocket.GetStream())))
{
outputStream.WriteLine("HTTP/1.0 200 OK");
outputStream.WriteLine("Content-Type: application/octet-stream");
outputStream.WriteLine("Content-Disposition: attachment; filename=Hany.jpg");
outputStream.WriteLine("Content-Length: " + img.Length);
outputStream.WriteLine("Connection: close");
outputStream.WriteLine(""); // this terminates the HTTP headers
string imageContent = Convert.ToBase64String(File.ReadAllBytes(@"C:UsersMohamedDesktopHany.jpg"));
outputStream.Write(imageContent);
outputStream.Flush();
}
谢谢Kzrystof,我接受了你的提示,现在它可以在使用copyTo之前刷新StreamWriter,但我真的不知道这样做是否正确?你觉得怎么样?
using (Stream fs = File.Open(@"C:UsersMohamedDesktopHany.jpg", FileMode.Open))
{
StreamWriter OutputStream = new StreamWriter(new BufferedStream(someSocket.GetStream()));
OutputStream.WriteLine("HTTP/1.0 200 OK");
OutputStream.WriteLine("Content-Type: application/octet-stream");
OutputStream.WriteLine("Content-Disposition: attachment; filename=Hany.jpg");
OutputStream.WriteLine("Content-Length: " + img.Length);
OutputStream.WriteLine("Connection: close");
OutputStream.WriteLine(""); // this terminates the HTTP headers
OutputStream.Flush();
fs.CopyTo(OutputStream.BaseStream);
OutputStream.BaseStream.Flush();
OutputStream.Flush();
}