Monday, April 8, 2013

Upload file in MVC3 via Ajax

Ther are quite a few Jquery plugins that will upload file using ajax. Here i will write a quick sample for acheiving the same using jquery.form.js.

First thing's first. get jquery.form.js plugin. You can search for this in google. :)

Now that you have this pluging and included in the script,
Follow these  simple steps.
1) Create form
     @using (Html.BeginForm("ActionName", "Controller", FormMethod.Post, new { enctype = "multipart/form-data", id = "ajaxUploadForm" }))
{}

2) IN this form, u can place "file" element to browse and choose file.
3) Create one button with type "Submit"
4) JS script in same form
$(function () {
 $("#ajaxUploadForm").ajaxForm({
            iframe: true,
            type: 'POST',
            dataType: "json",
            cache: false,
            timeout: 1200000,
            async: false,
            beforeSubmit: function () {
                //Do something here if needed like show in progress message
            },
            success: function (result) {
                alert("sucess"
            },
            error: function (xhr, textStatus, errorThrown) {
                alert("Error uploading file");
            }
        });
 });


Done with form.

Create controller

public string ActionName(HttpPostedFileBase file)
        {
            string message = "File Uploaded Successfully";
            if (file != null && file.ContentLength > 0)
            {
     //file extensin can be checked with Path.GetExtension(file.FileName)
                    if (file!= null && file.ContentLength > 0)                   
      string fileName = Path.GetFileName(file.FileName);
      string basePath = ConfigurationManager.AppSettings["some path from config OR hardcode path"];
      string path = Path.Combine(basePath, fileName);
      Check for directory in the server. If not exist create one or manualy create required folder.
  
      file.SaveAs(path);                   
                }
            }
            else
            {
                message = "File is empty or null";
                return message;
            }
            return message;
        }


You are ready to go. You can return message in json format as your requirement, for sucess, some error while uploading etc etc.


Please check out my  blog to see how extra parameters can be passed to controller while uploading file.

Happy Coding

1 comment: