[英]Trying to upload a file using ajax in ASP.NET MVC
我正在使用ASP.NET MVC 3,我想使用ajax表單上傳圖像文件
我的索引視圖代碼是:
<% using (Ajax.BeginForm("Save","Home", new AjaxOptions() { HttpMethod = "POST", InsertionMode = InsertionMode.Replace }, new { enctype = "multipart/form-data" }))
{%>
<input type="file" /><input type ="submit" value="Submit File"/>
<% } %>
控制器代碼為:
[HttpPost]
public ActionResult Save()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View("Index");
}
當我上傳文件並單擊按鈕時,ajax表單已提交,但是我收到了Request.File.Count為0的信息。
MVC中默認的默認ajax不支持上傳文件。 您需要使用隱藏的iframe /插件(Flash,Silverlight ..)/ html5或它們的組合。
一些可以幫助您的腳本:
您可以使用@LukášNovotný建議的插件,也可以執行以下操作
這是我管理文件上傳的操作。 適用於大多數Ajaxy文件上傳器。 (我認為)
public ActionResult Upload(HttpPostedFileBase uploadfile)
{
try
{
var dr405 = new DR405Service().GetDR405ById(new DR405DBContext(), DR405Profile.CurrentUser.TangiblePropertyId);
var saveLocation = Path.Combine(DR405Service.SavePath + DR405Profile.CurrentUser.TangiblePropertyId);
System.IO.Directory.CreateDirectory(saveLocation);
if ((int)uploadfile.ContentLength / 1024 <= 15000)
{
uploadfile.SaveAs(Path.Combine(saveLocation, Path.GetFileName(uploadfile.FileName)));
var file = new dr405files { TangiblePropertyId = DR405Profile.CurrentUser.TangiblePropertyId, FileName = uploadfile.FileName, UploadDate = DateTime.Now };
//dr405.dr405files.Add(file);
//c.dr405s.Add(dr405);
db.Entry(file).State = file.FileId == 0 ? EntityState.Added : EntityState.Modified;
//db.Entry(dr405).State = EntityState.Modified;
new DR405Service().Save(db);
ViewData["UploadStatus"] = String.Format("File name: {0}, {1}Kb Uploaded Successfully.", uploadfile.FileName, (int)uploadfile.ContentLength / 1024);
}
else
{
ViewData["UploadStatus"] = String.Format("File exceeds 15MB upload limit. Please reduce size and try again.", uploadfile.FileName);
}
}
catch (Exception ex)
{
ViewData.ModelState.AddModelError("_FORM", ex.ToString());
}
return View();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.