首页 > 解决方案 > asp.net ajax 上传文件总是为空

问题描述

我正在尝试使用 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;
            }
        }
    }
}

标签: htmljqueryasp.netajaxhttppostedfilebase

解决方案


我检查了你的代码,一切都在为我工作。

让我分享一些截图:

处理程序获取文件:
处理程序获取文件

项目结构:
项目结构

HTML页面:
网页


推荐阅读