Search This Blog

Saturday 6 April 2019

Upload File using Jquery AJAX in Asp.net


Step 1: - Open Visual Studio 2015 => Go to File Menu => New => Project...

Step 2: - In the Installed Templates list, select Visual C# => Web

Step 3: - Select ASP.Net Web Application (.NET Framework) from the Web list => Type UploadFileJqueryAJAX in the Name box and click OK

Step 4: - Select Empty template from ASP.NET Templates List and Check Web Forms check box under Add folders and core references for:






























Step 5: - Right Click on Project Root folder => Add => New Items... => Expand Visual C# from Left Pane and Select Web => Select Web Form from Middle Pane => Type FileUpload.aspx in Name box => Click Add

Step 6: - Copy Past following Html in FileUpload.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUpload.aspx.cs" Inherits="UploadFileJqueryAJAX.FileUpload" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Upload File using Jquery AJAX in Asp.net</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#FileUpload1").change(function () {
                var fileUpload = $("#FileUpload1").get(0);
                var files = fileUpload.files;

                if (files && files[0]) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        $("#Image1").attr("src", e.target.result);
                    }
                    reader.readAsDataURL(files[0]);
                }
            });

            $("#btnUpload").click(function (e) {
                var fileUpload = $("#FileUpload1").get(0);
                var files = fileUpload.files;

                var data = new FormData();
                if (files.length > 0) {
                    data.append(files[0].name, files[0]);
                }

                $.ajax({
                    url: "FileUploadHandler.ashx",
                    type: "POST",
                    data: data,
                    contentType: false,
                    processData: false,
                    success: function (result) {
                        alert(result);
                    },
                    error: function (err) {
                        alert(err.statusText)
                    }
                });
                e.preventDefault();
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table border="1">
                <caption>Upload File using Jquery AJAX in Asp.net</caption>
                <tr>
                    <td>Browse File:</td>
                    <td>
                        <asp:FileUpload ID="FileUpload1" runat="server" ClientIDMode="Static" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <fieldset>
                            <legend>Preview Upload</legend>
                            <asp:Image ID="Image1" runat="server" Src="#" Height="150px" Width="150px" AlternateText="No Image" ClientIDMode="Static" />
                        </fieldset>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Button ID="btnUpload" runat="server" Text="Upload File" ClientIDMode="Static" />
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

Step 7: - Preview look like this


















Step 8: - Right Click on Project Root folder => Add => New Items... => Expand Visual C# from Left Pane and Select Web => Select Generic Handler from Middle Pane => Type FileUploadHandler.ashx in Name box => Click Add

Step 9: - Copy Past following code in FileUploadHandler.ashx

using System.IO;
using System.Web;

namespace UploadFileJqueryAJAX
{
    /// <summary>
    /// File Upload Handler
    /// </summary>
    public class FileUploadHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Files.Count > 0)
            {
                HttpFileCollection files = context.Request.Files;
                for (int i = 0; i < files.Count; i++)
                {
                    string filePath = context.Server.MapPath("~/UploadFiles/");
                    HttpPostedFile file = files[i];
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    string fileName = filePath + file.FileName;
                    file.SaveAs(fileName);
                }
                context.Response.ContentType = "application/octet-stream";
                context.Response.Write("File Uploaded Successfully!");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

Step 10: - Browse file => Click Upload File

Note: - You will be received alert “File Uploaded Successfully!