用 Console 实现 Web Server 支持上传文件组件 plupload
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.SelfHost;
namespace wpsto
{
public class FileHandler : DelegatingHandler
{
private MediaTypeHeaderValue GuessMediaTypeFromExtension(string path)
{
var ext = Path.GetExtension(path);
switch (ext)
{
case ".htm":
case ".html":
return new MediaTypeHeaderValue(MediaTypeNames.Text.Html);
case ".css":
return new MediaTypeHeaderValue("text/css");
case ".js":
return new MediaTypeHeaderValue("text/javascript");
default:
return new MediaTypeHeaderValue("application");
}
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.RequestUri.AbsolutePath.StartsWith("/kmsapi"))
return base.SendAsync(request, cancellationToken);
return Task<HttpResponseMessage>.Factory.StartNew(() =>
{
var response = request.CreateResponse();
//var baseFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var suffix = (request.RequestUri.AbsolutePath == "" || request.RequestUri.AbsolutePath == "/") ? "kms.html" : request.RequestUri.AbsolutePath.Substring(1).Replace("/", "\\");
var fullPath = Path.Combine(PathHelper.kmsroot, System.Web.HttpUtility.UrlDecode(suffix));
if (System.IO.File.Exists(fullPath))
{
response.Content = new StreamContent(new FileStream(fullPath, FileMode.Open));
if (suffix.IndexOf(".html") != -1 && suffix.IndexOf(".htm") != -1)
response.Content.Headers.ContentType = GuessMediaTypeFromExtension(fullPath);
}
else
response.Content = new StringContent("没有这个文件");
return response;
});
}
}
public class HttpWebApi
{
public static void Run()
{
var config = new HttpSelfHostConfiguration("http://localhost:8888");
config.Routes.MapHttpRoute(
"kmsapi", "kmsapi/{controller}/{cmd}",
new { cmd = RouteParameter.Optional });
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.None;
config.MessageHandlers.Add(new FileHandler());
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.MaxConcurrentRequests = 1000;
config.MaxReceivedMessageSize = int.MaxValue;
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
Console.WriteLine(config.MaxReceivedMessageSize);
server.OpenAsync().Wait();
Console.WriteLine("监听Http请求.http://localhost:8888");
Console.WriteLine("按任意键退出.");
Console.ReadLine();
}
}
}
public class KmsController : ApiController
{
public Task<HttpResponseMessage> post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = PathHelper.kmstemp;
var provider = new MultipartFormDataStreamProvider(root);
foreach (KeyValuePair<string, string> one in Request.GetQueryNameValuePairs())
{
Console.WriteLine(one.Key + " " + one.Value);
}
// Read the form data and return an async task.
var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Console.WriteLine(file.Headers.ContentDisposition.FileName);
Console.WriteLine("Server file path: " + file.LocalFileName);
if (string.IsNullOrEmpty(file.Headers.ContentDisposition.FileName))
{
return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
}
string fileName = file.Headers.ContentDisposition.FileName;
if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
{
fileName = fileName.Trim('"');
}
if (fileName.Contains(@"/") || fileName.Contains(@"\"))
{
fileName = System.IO.Path.GetFileName(fileName);
}
if (System.IO.File.Exists(System.IO.Path.Combine(PathHelper.kmstemp, fileName)))
System.IO.File.Delete(System.IO.Path.Combine(PathHelper.kmstemp, fileName));
System.IO.File.Move(file.LocalFileName, System.IO.Path.Combine(PathHelper.kmstemp, fileName));
}
return Request.CreateResponse(HttpStatusCode.OK);
});
return task;
}
public string get()
{
return "server is ok";
}
}
}