尝试在ASP.NET MVC中使用ajax上传文件

时间:2011-12-22 12:22:17

标签: javascript ajax asp.net-mvc-3

我正在使用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。

3 个答案:

答案 0 :(得分:0)

mvc中默认不显眼的ajax不支持上传文件。您需要使用隐藏的iframe /插件(flash,silverlight ..)/ html5或其组合。

一些可能对您有帮助的脚本:

答案 1 :(得分:0)

您可以使用@LukášNovotný建议的插件,否则您可以执行以下操作

  • 创建通用HTTP处理程序uploadfile.ashx
  • 将数据发布到文件中(设置表单action =“yourpath / UploadFile.ashx”
  • 在处理程序中,您可以将文件读取为 HttpPostedFile uploadedfile = context.Request.Files [0];

答案 2 :(得分:0)

这是我管理文件上传的Action。适用于大多数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();
        }