Saturday 6 December 2014

File upload using MVC 4 with Ajax

<html>
    <head>
    <title>Upload Example</title>
        <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#Upload").click(function () {
                var formData = new FormData();
                var totalFiles = document.getElementById("FileUpload").files.length;
                for (var i = 0; i < totalFiles; i++) {
                    var file = document.getElementById("FileUpload").files[i];

                    formData.append("FileUpload", file);
                }
                $.ajax({
                    type: "POST",
                    url: '/Home/Upload',
                    data: formData,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success: function (response) {
                        alert('succes!!');
                    },
                    error: function (error) {
                        alert("errror");
                    }
                });
            });
        });

</script>
</head>
<body>
    <input type="file" id="FileUpload" multiple />
    <input type="button" id="Upload" value="Upload" />
</body>
</html>
MVC CODE

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication12.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public void Upload()
        {
            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];

                var fileName = Path.GetFileName(file.FileName);

                var path = Path.Combine(Server.MapPath("~/Junk/"), fileName);
                file.SaveAs(path);
            }

        }
}
}

No comments:

Post a Comment