Upload and save File in Folder (Directory) using AJAX FormData and Generic Handler in ASP.Net

Last Reply 10 days ago By dharmendr

Posted 10 days ago

hello,

i am using this solution Upload File using FormData and AJAX in ASP.Net

it works in outside page like url/default.aspx

but the same code not working if use in url/news/feed.aspx

it sents blank file name

please advice

    <input type="file" name="postedFile" />
    <input type="button" id="btnUpload" value="Upload" />
    <progress id="fileProgress" style="display: none"></progress>
    <hr />
    <span id="lblMessage" style="color: Green"></span>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $("body").on("click", "#btnUpload", function () {
            $.ajax({
                url: 'HandlerCS.ashx',
                type: 'POST',
                data: new FormData($('form')[0]),
                cache: false,
                contentType: false,
                processData: false,
                success: function (file) {
                    $("#fileProgress").hide();
                    $("#lblMessage").html("<b>" + file.name + "</b> has been uploaded.");
                },
                xhr: function () {
                    var fileXhr = $.ajaxSettings.xhr();
                    if (fileXhr.upload) {
                        $("progress").show();
                        fileXhr.upload.addEventListener("progress", function (e) {
                            if (e.lengthComputable) {
                                $("#fileProgress").attr({
                                    value: e.loaded,
                                    max: e.total
                                });
                            }
                        }, false);
                    }
                    return fileXhr;
                }
            });
        });
    </script>

 

<%@ WebHandler Language="C#" Class="HandlerCS" %>

using System;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;

public class HandlerCS : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        //Check if Request is to Upload the File.
        if (context.Request.Files.Count > 0)
        {
            //Fetch the Uploaded File.
            HttpPostedFile postedFile = context.Request.Files[0];
            
            //Set the Folder Path.
            string folderPath = context.Server.MapPath("~/Uploads/");

            //Set the File Name.
            string fileName = Path.GetFileName(postedFile.FileName);
            
            //Save the File in Folder.
            postedFile.SaveAs(folderPath + fileName);

            //Send File details in a JSON Response.
            string json = new JavaScriptSerializer().Serialize(
                new
                {
                    name = fileName
                });
            context.Response.StatusCode = (int)HttpStatusCode.OK;
            context.Response.ContentType = "text/json";
            context.Response.Write(json);
            context.Response.End();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
You are viewing reply posted by: dharmendr 10 days ago.
Posted 10 days ago

Hi nauna,

Refer the sample code.

HTML

feed.aspx

<input type="file" name="postedFile" />
<input type="button" id="btnUpload" value="Upload" />
<progress id="fileProgress" style="display: none"></progress>
<hr />
<span id="lblMessage" style="color: Green"></span>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $("body").on("click", "#btnUpload", function () {
        $.ajax({
            url: '<%= ResolveUrl("~/HandlerCS.ashx")%>',
            type: 'POST',
            data: new FormData($('form')[0]),
            cache: false,
            contentType: false,
            processData: false,
            success: function (file) {
                $("#fileProgress").hide();
                $("#lblMessage").html("<b>" + file.name + "</b> has been uploaded.");
            },
            xhr: function () {
                var fileXhr = $.ajaxSettings.xhr();
                if (fileXhr.upload) {
                    $("progress").show();
                    fileXhr.upload.addEventListener("progress", function (e) {
                        if (e.lengthComputable) {
                            $("#fileProgress").attr({
                                value: e.loaded,
                                max: e.total
                            });
                        }
                    }, false);
                }
                return fileXhr;
            }
        });
    });
</script>

Handler

<%@ WebHandler Language="C#" Class="HandlerCS" %>

using System;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;

public class HandlerCS : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //Check if Request is to Upload the File.
        if (context.Request.Files.Count > 0)
        {
            //Fetch the Uploaded File.
            HttpPostedFile postedFile = context.Request.Files[0];

            //Set the Folder Path.
            string folderPath = context.Server.MapPath("~/Uploads/");

            //Set the File Name.
            string fileName = Path.GetFileName(postedFile.FileName);

            //Save the File in Folder.
            postedFile.SaveAs(folderPath + fileName);

            //Send File details in a JSON Response.
            string json = new JavaScriptSerializer().Serialize(new { name = fileName });
            context.Response.StatusCode = (int)HttpStatusCode.OK;
            context.Response.ContentType = "text/json";
            context.Response.Write(json);
            context.Response.End();
        }
    }

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

Page is inside news folder which is inside the url folder.

Url will be ../user/feed.aspx