htmljqueryasp.netajaxhttppostedfilebase

asp.net ajax upload file always get null


I am trying to upload a file using jquery ajax, I can see the file object, its name, its size, etc.

In console by formdata.get("files"), but the context.request.files size is always zero, it seems the server does not receive the file from client, the HttpPostedFileBase request is always null.

How to fix it?

HTML:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadKpData.aspx.cs" Inherits="WebApp.Admin.UploadKpData" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script type="text/javascript" src="./../Scripts/jquery-1.4.4.min.js"></script>
</head>

<body>
    <div>
        <div>
            <input type="file" id="kpData"/>
            <button type="submit" id="uploadKp" />
        </div>
    </div>
</body>
<script>

    $("#uploadKp").click(function () {
        var formdata = new FormData();
        var files = $("#kpData").get(0).files[0];
        formdata.append("files", files);
        $.ajax({
            url: "../../ds/UploadExcel.ashx",
            type: "POST",
            async: false,
            contentType: false, // Not to set any content header  
            processData: false, // Not to process data  
            data: formdata,
            success: function (result) {
                alert(result);
            },
            error: function (err) {
                alert(err.statusText);
            }
        });

    })
</script>
</html>

UploadExcel.ashx:

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

namespace WebApp.ds
{
    
    public class UploadExcel : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpFileCollection file = context.Request.Files;
            HttpPostedFile file1 = file[0];
            string fileName = context.Server.MapPath("~/tmp/" + "test2.xlsx");
            file1.SaveAs(fileName);
            context.Response.ContentType = "text/plain";
        }

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

Solution

  • I have checked your code and all are working for me.

    Let me share some screenshots :

    Handler get file:
    Handler get file

    Project structure:
    Project structure

    HTML page:
    HTML page