Загрузка файлов на веб-сервер - C#
Формулировка задачи:
Здравствуйте, написал простенький локальный веб-сервер, но вот такая вот проблема: не получается загрузить файлы на сервер, хотя на html и php вроде все правильно реализовал(хотя и признаю что вообще в php это мой первый код и то копипастом) возможно что то нужно дописать на сервере но пока понять не могу, вот код сервера:
если что вот исходники:
class Server
{
public bool running = false;
private int timeout = 8;
private Encoding charEncoder = Encoding.UTF8;
private Socket serverSocket;
private string contentPath;
private Dictionary<string, string> extensions = new Dictionary<string, string>()
{
{ "htm", "text/html" },
{ "html", "text/html" },
{ "xml", "text/xml" },
{ "txt", "text/plain" },
{ "css", "text/css" },
{ "png", "image/png" },
{ "gif", "image/gif" },
{ "jpg", "image/jpg" },
{ "jpeg", "image/jpeg" },
{ "zip", "application/zip" },
{ "rar", "application/rar" },
{ "mpg", "image/mpg" },
{ "MOV", "image/mov" }
};
public bool start(IPAddress ipAddress, int port, int maxNOfCon, string contentPath)
{
if (running) return false;
try
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(ipAddress, port));
serverSocket.Listen(maxNOfCon);
serverSocket.ReceiveTimeout = timeout;
serverSocket.SendTimeout = timeout;
running = true;
this.contentPath = contentPath;
}
catch { return false; }
Thread requestListenerT = new Thread(() =>
{
while (running)
{
Socket clientSocket;
try
{
clientSocket = serverSocket.Accept();
Thread requestHandler = new Thread(() =>
{
clientSocket.ReceiveTimeout = timeout;
clientSocket.SendTimeout = timeout;
try { handleTheRequest(clientSocket); }
catch
{
try { clientSocket.Close(); } catch { }
}
});
requestHandler.Start();
}
catch{}
}
});
requestListenerT.Start();
return true;
}
public void stop()
{
if (running)
{
running = false;
try { serverSocket.Close(); }
catch { }
serverSocket = null;
}
}
private void handleTheRequest(Socket clientSocket)
{
byte[] buffer = new byte[10240];
int receivedBCount = clientSocket.Receive(buffer);
string strReceived = charEncoder.GetString(buffer, 0, receivedBCount);
string httpMethod = strReceived.Substring(0, strReceived.IndexOf(" "));
int start = strReceived.IndexOf(httpMethod) + httpMethod.Length + 1;
int length = strReceived.LastIndexOf("HTTP") - start - 1;
string requestedUrl = strReceived.Substring(start, length);
string requestedFile;
if (httpMethod.Equals("GET") || httpMethod.Equals("POST"))
requestedFile = requestedUrl.Split('?')[0];
{
notImplemented(clientSocket);
return;
}
requestedFile = requestedFile.Replace("/", "").Replace("\\..", "");
start = requestedFile.LastIndexOf('.') + 1;
if (start > 0)
{
length = requestedFile.Length - start;
string extension = requestedFile.Substring(start, length);
if (extensions.ContainsKey(extension))
if (File.Exists(contentPath + requestedFile))
sendOkResponse(clientSocket, File.ReadAllBytes(contentPath + requestedFile), extensions[extension]);
else
notFound(clientSocket);
}
else
{
if (requestedFile.Substring(length - 1, 1) != "")
requestedFile += "";
if (File.Exists(contentPath + requestedFile + "index.htm"))
sendOkResponse(clientSocket, File.ReadAllBytes(contentPath + requestedFile + "\\index.htm"), "text/html");
else if (File.Exists(contentPath + requestedFile + "index.html"))
sendOkResponse(clientSocket, File.ReadAllBytes(contentPath + requestedFile + "\\index.html"), "text/html");
else
notFound(clientSocket);
}
}
private void notImplemented(Socket clientSocket)
{
sendResponse(clientSocket, "<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body><h2>Simple Web Server</h2><div>501 - Method Not Implemented</div></body></html>", "501 Not Implemented", "text/html");
}
private void notFound(Socket clientSocket)
{
sendResponse(clientSocket, "<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body><h2>Simple Web Server</h2><div>404 - Not Found</div></body></html>", "404 Not Found", "text/html");
}
private void sendOkResponse(Socket clientSocket, byte[] bContent, string contentType)
{
sendResponse(clientSocket, bContent, "200 OK", contentType);
}
private void sendResponse(Socket clientSocket, string strContent, string responseCode, string contentType)
{
byte[] bContent = charEncoder.GetBytes(strContent);
sendResponse(clientSocket, bContent, responseCode, contentType);
}
private void sendResponse(Socket clientSocket, byte[] bContent, string responseCode, string contentType)
{
try
{
byte[] bHeader = charEncoder.GetBytes(
"HTTP/1.1 " + responseCode + "\r\n"
+ "Server: простой ВЭБсервер\r\n"
+ "Content-Length: " + bContent.Length.ToString() + "\r\n"
+ "Connection: close\r\n"
+ "Content-Type: " + contentType + "\r\n\r\n");
clientSocket.Send(bHeader);
clientSocket.Send(bContent);
clientSocket.Close();
}
catch { }
}
}Решение задачи: «Загрузка файлов на веб-сервер»
textual
Листинг программы
<html>
<head>
<title>Результат загрузки файла</title>
</head>
<body>
<?php
if($_FILES["filename"]["size"] > 1024*3*1024)
{
echo ("Размер файла превышает три мегабайта");
exit;
}
if(is_uploaded_file($_FILES["filename"]["tmp_name"]))
{
move_uploaded_file($_FILES["filename"]["tmp_name"], "/path/to/file/".$_FILES["filename"]["name"]);
} else {
echo("Ошибка загрузки файла");
}
?>
</body>
</html>