no

How to Upload a File in an Mvc3 C# Ajax Form

It's easy to upload file in a synchronous form, where you just post the file and read a HttpPostedFile variable in the server side: In ...

It's easy to upload file in a synchronous form, where you just post the file and read a HttpPostedFile variable in the server side: In plain html form, take note of the form enctype property:
//the view (index.cshtml)
@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    
    
}

public class FileController : Controller
{    
    //it should show index.cshtml view
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(HttpPostedFile file)
    {
        if (file != null && file.ContentLength > 0) 
        {  //now you have a non-empty file
            //to save in a local directory
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Uploads"), fileName);
            file.SaveAs(path);
        }
        return new EmptyResult();       
    }
}
That should work no problem but what if you have an ajax form, asynchronously you will not be able to upload a file together with the other form fields. So I've used a 3rd party javascript library to create a hidden iframe that will contain a file field.
http://code.google.com/p/ajax-file-upload-struts2/source/browse/trunk/src/main/resources/template/com/davidjc/javascript/ajaxfileupload.js?r=4 So here's my implementation on uploading a file on an ajax form, using the javascript library I've mentioned above:
//index.cshtml view
<script src="@Url.Content("~/Scripts/ajaxfileupload.js")" type="text/javascript"></script>
<script type="text/javascript">
    function ajaxFileUpload() {
        $.ajaxFileUpload
  (
   {
       url: "@Url.Action("UploadAttachment", "File")",
       secureuri: false,
       fileElementId: 'FileUpload',
       dataType: 'json',
       data: {
                    Name: $('#Name').val(), //you can declare the other form elements here
                },
       success: function (data, status) {
           if (typeof (data.error) != 'undefined') {
               if (data.error != '') {
                   //alert(data.error);
               } else {
                   //alert(data.msg);
               }
           }
       },
       error: function (data, status, e) {
           //alert(e);
       }
   }
  )

        return false;
    }
@using (Ajax.BeginForm("Upload", "File", new { }, new AjaxOptions { }, new { enctype = "multipart/form-data" }))
{
</script>
<table> 
<tr>
        <td class="label">
            @Html.LabelFor(m => m.Name)
        </td>
        <td>
            <div class="field_container">
                @Html.TextBoxFor(m => m.Name)
            </div>
        </td>
    </tr>   
    <tr>
        <td class="label">
            @Html.LabelFor(m => m.PathToAttachment)
        </td>
        <td>
            <div class="field_container">
                @Html.TextBoxFor(m => m.FileUpload, new { type = "file" })
            </div>
        </td>
    </tr>
</table>

}

public class FileController : Controller
{    
    //it should show index.cshtml view
    public ActionResult Index()
    {
        return View();
    }

    //do nothing on form submit
    [HttpPost]
    public ActionResult AddAttachment(AttachmentModel model)
    {
        return Json(new { success = true });
    }
//this is where the file gets save in the server
public ActionResult UploadAttachment(String Name, HttpPostedFile FileUpload)
        {
            if (FileUpload.ContentLength > 0)
            {
                var r = new Random();
                var uploadPath = Server.MapPath("~/Uploads");
                var filename = FileName.Replace("_", "");
                var savedFileName = Path.Combine(uploadPath, Path.GetFileName(filename));
                //now you have your file
            }
            return new EmptyResult();
        }
}

Related

c# 6274800264803644615

Post a Comment Default Comments

3 comments

Anonymous said...

at a glance, I see you're missing the ";" at the end of the script (prior to the "return false;"
Also your script end tag has ended up in the wrong place

Anonymous said...

do you have download'able code for this`?
The example seems rather unfinished...
I don't see the jquery being called anywhere...

Srikanth said...


method parameter are showing null after post.

UploadAttachment(String FirstName, String LastName, HttpPostedFile Attachment)

$.ajaxFileUpload(
{
url: "/ContactSubmission/UploadAttachment",
secureuri: false,
fileElementId: 'Attachment',
dataType: 'json',
data: {
FirstName: $('#FirstName').val(), //you can declare the other form elements here
LastName: $('#LastName').val()
},
success: function(data, status) {
alert(data);
if (typeof(data.error) != 'undefined') {
if (data.error != '') {
//alert(data.error);
} else {
//alert(data.msg);
}
}
},
error: function(data, status, e) {
//alert(e);
}
}
);

item