Trying to upload a file using ajax in ASP.NET MVC

I am using ASP.NET MVC 3, I want to upload a image file using an ajax form

My Index view code is:

 <% 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"/>
   <% } %>

and Controller code is:

[HttpPost]
public ActionResult Save()
{
   ViewBag.Message = "Welcome to ASP.NET MVC!";
   return View("Index");
}

When I upload a file and click on the button, the ajax form is submitted, but i am getting a Request.File.Count of 0.


Default unobtrusive ajax in mvc doesn't support uploading files. You need to use hidden iframe/plugin (flash, silverlight..)/html5 or combination of those.

Some scripts that might help you:

  • http://valums.com/ajax-upload/
  • http://www.uploadify.com/

  • You can use the the plugins suggested by @Lukáš Novotný or else you can do the following

  • Create an Generic HTTP handler uploadfile.ashx
  • Post the data to the file(set the form action="yourpath/UploadFile.ashx"
  • In the handler you can read the file as HttpPostedFile uploadedfile = context.Request.Files[0];

  • Here's my Action that manages the file uploads. Would work with most Ajaxy file uploaders. (I think)

    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();
            }
    
    链接地址: http://www.djcxy.com/p/62766.html

    上一篇: 当数据被重新发布时,MVC如何填充模型

    下一篇: 尝试在ASP.NET MVC中使用ajax上传文件