asp.net ajax上传文件始终为null

问题描述

我正在尝试使用jquery ajax上传文件,我可以看到文件对象,其名称,大小等。

在控制台中使用formdata.get("files"),但是context.request.files的大小始终为零,似乎服务器未从客户端接收文件HttpPostedFileBase请求始终为空。

如何解决

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>

上传Excel.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;
            }
        }
    }
}

谢谢!

解决方法

我已经检查了您的代码,所有人都在为我工作。

让我分享一些屏幕截图:

Handler get file

Project structure

HTML page