我正在开发一种使用asp.net mvc 4 web api的服务。在一个表单上,用户必须上传几个文件,然后提交表单到服务器。问题出现在使用ajax上传文件到asp.net mvc web api上。我已经实现了不使用ajax的上传。但是我需要使用ajax来完成它。
以下是实现:
public Task<HttpResponseMessage> PostJob()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
string path = HttpContext.Current.Server.MapPath(string.Format("~/Resources/Documents"));
MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(path);
var request = Request.Content.ReadAsMultipartAsync(provider);
var task = request.ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
string fileName = provider.BodyPartFileNames.FirstOrDefault().Value;
string originalName = provider.BodyPartFileNames.FirstOrDefault().Key.TrimStart('"').TrimEnd('"');
string RandomName = provider.BodyPartFileNames.First().Value + Path.GetExtension(originalName);
FileInfo file = new FileInfo(fileName);
file.CopyTo(Path.Combine(path, originalName), true);
file.Delete();
return new HttpResponseMessage(HttpStatusCode.Created);
});
我找到了一篇使用HTML5实现此功能的文章,链接为http://www.strathweb.com/2012/04/html5-drag-and-drop-asynchronous-multi-file-upload-with-asp-net-webapi/。我需要它在IE8中运行。也许你有什么想法吗?
非常感谢您的帮助, Iryna。