我目前正在使用流读写器来将文件读写到网页上。当前.html文件正在运行,但是.jpg和任何类型的图像都无法发布。
我将如何能够像mimetype映射一样提供文件?
namespace wdd_assign_07_github
{
class Program
{
static void Main(string[] args)
{
//TcpListener server = null;
if (args == null)
{
Console.WriteLine("args is null");
}
else if (args.Length != 3)
{
Console.WriteLine("Not enough arguments");
}
else
{
//do nothing
}
string webRoot = args[0].Substring(args[0].LastIndexOf("=") + 1);
string webIP = args[1].Substring(args[1].LastIndexOf("=") + 1);
string webPort = args[2].Substring(args[2].LastIndexOf("=") + 1);
int numWebPort = Int32.Parse(webPort);
Int32 port = numWebPort;
TcpListener listener = new TcpListener(port);
listener.Start();
while (true)
{
//performing a blocking vall to accept requests
Console.WriteLine("Waiting for a connection");
TcpClient client = listener.AcceptTcpClient();
StreamReader sr = new StreamReader(client.GetStream());
StreamWriter sw = new StreamWriter(client.GetStream());
try
{
//client makes a request
//lets handle that request
string request = sr.ReadLine();
//lets print that out on our server console
Console.WriteLine(request);
//lets split that request
//[0]GET [1]PAGE [2]HTTPstring
string[] tokens = request.Split(' ');
string page = tokens[1];
//lets check if they requested the dedault page or not
if (page == "/")
{
page = "<H1>This is the default page</H1>";
}
//lets find the file now
StreamReader file = new StreamReader(webRoot + page);
sw.WriteLine("HTTP/1.0 200 OK\n");
//lets send the file
string data = file.ReadLine();
//while data doesnt equal null
while (data != null)
{
sw.WriteLine(data);
sw.Flush();
data = file.ReadLine();
}
}
catch (Exception e)
{
//error
sw.WriteLine("HTTP/1.0 404 OK\n");
sw.WriteLine("<H1>SORRY! We couldnt find your file</H1>");
sw.Flush();
}
client.Close();
}
}
}
}
您应该考虑很多事情:
Content-Type
和Content-Type
标头。Content-Length
Content-Length
代替var mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
{".jpg", "image/jpeg"},
{".html", "text/html"},
{".js", "application/javascript"},
// ...
};
// later in your method
var ext = Path.GetExtension(page);
var contentType = mappings[ext]; // may throw if mapping is missing
(至少对于jpg和png这样的二进制文件)