我在asp.net MVC项目中有以下IRouteHandler类,用于通过ajax上传文件:
public class UploadHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
HttpHandler httpHandler = new HttpHandler();
return httpHandler;
}
public class HttpHandler : IHttpHandler
{
#region IHttpHandler Members
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0)
{
HttpFileCollection SelectedFiles = context.Request.Files;
for (int i = 0; i < SelectedFiles.Count; i++)
{
HttpPostedFile PostedFile = SelectedFiles[i];
string FileName = context.Server.MapPath("~/Content/uploads/" + PostedFile.FileName);
PostedFile.SaveAs(FileName);
}
}
else
{
context.Response.ContentType = "text/plain";
context.Response.Write("Please Select Files");
}
context.Response.ContentType = "text/plain";
context.Response.Write("Files Uploaded Successfully!!");
}
#endregion
}
}
和javascript:
var uploadfiles = $("#upFile").get(0);
var uploadedfiles = uploadfiles.files;
var fromdata = new FormData();
for (var i = 0; i < uploadedfiles.length; i++) {
fromdata.append(uploadedfiles[i].name, uploadedfiles[i]);
}
var choice = {};
choice.url = "Upload";
choice.type = "POST";
choice.data = fromdata;
choice.contentType = false;
choice.processData = false;
choice.success = function (result) {
for (var i = 0; i < uploadedfiles.length; i++) {
model.Filename(uploadedfiles[i].name);
}
$("#lblWait").hide();
};
choice.error = function (err) { alert(err.statusText); };
$.ajax(choice);
在App_Start / RouteConfig.cs中:
routes.Add(new Route("Upload", new UploadHandler()));
但是ajax只是给了一个资源无法找到所以我认为我的路由有些不对劲,有人能指出我正确的方向吗?
答案 0 :(得分:0)
最后通过使用控制器操作来实现这一点,如:
[HttpPost]
public void UploadFile()
{
var context = HttpContext.Current;
if (context.Request.Files.Count > 0)
{
HttpFileCollection SelectedFiles = context.Request.Files;
for (int i = 0; i < SelectedFiles.Count; i++)
{
HttpPostedFile PostedFile = SelectedFiles[i];
string FileName = context.Server.MapPath("~/Content/uploads/" + PostedFile.FileName);
PostedFile.SaveAs(FileName);
}
}
else
{
context.Response.ContentType = "text/plain";
context.Response.Write("Please Select Files");
}
context.Response.ContentType = "text/plain";
context.Response.Write("Files Uploaded Successfully!!");
}