You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET ASPX WebForms提交含文件表格数据失败,WebMethod未触发

问题原因分析
  1. 前后端数据格式不匹配:前端发送multipart/form-data类型的FormData,但后端SaveFiles方法期望接收名为jsonData的JSON字符串参数,且ASP.NET WebMethod默认要求请求内容类型为application/json,导致请求无法被正确解析,断点未触发并返回错误HTML。
  2. 文件传输方式错误:前端存储的document_Name是File对象,无法直接序列化为JSON,即便强行转为JSON发送也会丢失文件数据。
  3. 参数设计不匹配:前端发送productTypes[]、productNames[]、files[]数组数据,后端却等待单一JSON字符串参数,两者完全不兼容。

解决方案

后端修改(ThirdPartyProductDocsUpload.aspx.cs)

重写SaveFiles方法,直接从Request中获取表单数据与上传文件,无需依赖JSON参数:

[WebMethod]
public static string SaveFiles()
{
    try
    {
        var request = HttpContext.Current.Request;
        string[] productTypes = request.Form.GetValues("productTypes[]");
        string[] productNames = request.Form.GetValues("productNames[]");
        HttpFileCollection files = request.Files;

        // 校验参数完整性
        if (productTypes == null || productNames == null || files.Count == 0 || productTypes.Length != files.Count)
        {
            throw new ArgumentException("输入参数不匹配或为空");
        }

        string uploadPath = HttpContext.Current.Server.MapPath("~/TPPUploadFiles/");
        // 确保上传目录存在
        if (!Directory.Exists(uploadPath))
        {
            Directory.CreateDirectory(uploadPath);
        }

        // 遍历处理每条记录与对应文件
        for (int i = 0; i < files.Count; i++)
        {
            HttpPostedFile file = files[i];
            if (file.ContentLength == 0)
                continue;

            string productType = productTypes[i];
            string productName = productNames[i];

            if (string.IsNullOrEmpty(productType) || string.IsNullOrEmpty(productName))
            {
                throw new ArgumentException($"第{i+1}条记录的产品类型或名称为空");
            }

            // 自定义文件名避免重名(可按需调整规则)
            string fileName = $"{productType}_{productName}_{Path.GetFileName(file.FileName)}";
            string filePath = Path.Combine(uploadPath, fileName);
            
            file.SaveAs(filePath);
        }

        return "文件上传成功";
    }
    catch (Exception ex)
    {
        return $"错误: {ex.Message}";
    }
}

前端修改(提交按钮事件)

调整Fetch请求,保留FormData传输方式,适配后端的参数接收逻辑:

document.getElementById("submitBtn").addEventListener("click", function () {
    var formData = new FormData();

    tableData.forEach(function (entry) {
        formData.append('productTypes[]', entry.product_Type);
        formData.append('productNames[]', entry.product_Name);
        formData.append('files[]', entry.document_Name);
    });

    fetch("ThirdPartyProductDocsUpload.aspx/SaveFiles", {
        method: "POST",
        body: formData
        // 无需手动设置Content-Type,浏览器会自动添加带边界符的multipart/form-data头部
    })
    .then(response => response.text().then(text => JSON.parse(text).d))
    .then(data => {
        console.log("服务器响应: " + data);
        alert(data); // 可选:给用户直观提示
    })
    .catch(error => {
        console.log("错误: " + error);
        alert("上传失败,请查看控制台日志");
    });
});

额外注意事项
  1. 确保项目中~/TPPUploadFiles/目录存在,后端代码已包含自动创建目录的逻辑。
  2. 在web.config中配置合理的文件上传大小限制(示例为1GB):
<system.web>
    <httpRuntime maxRequestLength="1048576" />
</system.web>
<system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="1073741824" />
        </requestFiltering>
    </security>
</system.webServer>
  1. 确认前端全局变量tableData的添加、删除操作能正确维护数组数据。

内容的提问来源于stack exchange,提问作者Ashley Ferns

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 08:45:03