File Upload Using Ajax ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Tuesday, 19 April 2016

File Upload Using Ajax

03:34:00 Posted by raviteja swayampu , 1 comment
Hello Every in this tutorial i am gonna teach you How to upload a file using Ajax without page refresh by using a  ajax file upload jquery Addon or plugn.These plugins increases the functionality of jquery.Before going in deep we need to know what is File Upload Plugin.
What is Jquery file upload plugin:
It is an ajax enabled jquery plugin for uploading,
  • Images(includes jpg,png,gif etc)
  • Documents,
  • PDF's,
and so on.........
It is very easy t o use..
we can upload multiple files at a time (i will discuss multiple file uploads later).
built-in validation rules.
these are the features of the jquery file upload plug in .
Now i will explain this by doing a sample file upload example in step by step manner.

Step 1:
1.Create a Mvc Application using Empty MVC template.
2.name it.

Step 2:
1.Add a Model class to the Model folder.
2.model.cs

public class MyModel
    {
        public HttpPostedFileBase file { get; set; }
    }

3.I added a property 'file' of type "HttpPostedFileBase" for Model binding.

Step 3:
1.Add a Controller for rendering View..
2.HomeController.cs

public ActionResult Index()
        {           
            return View();
        }
Step 4:
1.Before that add the libreary files of jquery and file upload plugin files.


2.Add reference this files in _Layout.cshtml page like below.


Step 5: 
1.Add controller for handling file uploads
2.name it as 'FileUpload'.
3.This method must be specified as [HttpPost] .Because it receives data from View page.
4.I also created a extra method for creating a directory for saving the uploaded files.(If you added a upload folder in Solution this method is not required).
FileController.cs:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace TestAjaxUpload
{
    public class FileController : Controller
    {
        [HttpPost]
        public  ActionResult UploadFile()
        {
            HttpPostedFileBase myFile = Request.Files["MyFile"];
            bool isUploaded = false;
            string message = "File upload failed";

            if (myFile != null && myFile.ContentLength != 0)
            {
                string pathForSaving = Server.MapPath("~/Uploads");
                if (this.CreateFolderIfNeeded(pathForSaving))
                {
                    try
                    {
                        myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName));
                        isUploaded = true;
                        message = "File uploaded successfully!";
                    }
                    catch (Exception ex)
                    {
                        message = string.Format("File upload failed: {0}", ex.Message);
                    }
                }
            }
            return Json(new { isUploaded = isUploaded, message = message }, "text/html");
        }
        //This method create a directory for saving files.
        private bool CreateFolderIfNeeded(string path)
        {
            bool result = true;
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception)
                {
                    result = false;
                }
            }
            return result;
        }
    }
}
Step 6:
1.Replace the index view code with following to display upload form.
@model MyModel
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<p>
    <input type="text" id="tbx-file-path" value="No file chosen..." readonly="readonly" />
    <span class="btn btn-success fileinput-button">
        <span>Select file...</span>
        @Html.TextBoxFor(m => m.file, new { id = "file-upload", type = "file" })
    </span>
</p>
<p><a class="btn btn-primary" href="#" id="start-upload-button">Start Upload</a></p>
Step 6:
1.Add jquery code in Index View page for ajax fileupload calling.

 var jqXHRData;
        $(document).ready(function () {
            'use strict';
            $('#file-upload').fileupload({
                url: '/File/UploadFile',
                dataType: 'json',
                add: function (e, data) {
                    jqXHRData = data
                },
                done: function (event, data) {
                    if (data.result.isUploaded) {
                        $("#tbx-file-path").val("No file chosen...");
                    }
                    else {

                    }
                    alert(data.result.message);
                },
                fail: function (event, data) {
                    if (data.files[0].error) {
                        alert(data.files[0].error);
                    }
                }
            });
        });
        $("#start-upload-button").on('click', function () {
            if (jqXHRData) {
                jqXHRData.submit();
            }
            return false;
        });
        $("#file-upload").on('change', function () {
            $("#tbx-file-path").val(this.files[0].name);
        });

Run the application you will get below screen.

select a file and click on 'start Upload' button.
file will upload and you can see the uploaded files here..


Downlaod code from here Downlaod.

Conclusion:
I hope this article helpful and understandable for every reader.If you have any suggestion please send me..

1 comment: