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

ASP.NET Core中Ajax上传图片至控制器,参数时而为null的原因排查

问题原因及解决方案

1. 按钮默认提交行为导致请求冲突

你的上传按钮是type="submit",点击后会触发所在表单的默认提交行为,页面会刷新,这会中断AJAX请求,导致控制器无法正确接收文件,出现参数为null的情况。

解决方法:

  • 方法一:在点击事件中阻止默认行为:
$('#uploadImage').on('click', function (e) {
    e.preventDefault(); // 阻止表单默认提交
    // 后续代码...
});
  • 方法二:将按钮类型改为button:
<button id="uploadImage" type="button" class="form-control form-control-lg btn btn-primary" style="color: white">Upload</button>

2. FormData作用域错误,未选择文件时仍发送请求

当前代码中FormData仅在用户选择文件时才定义,且未选择文件时没有终止AJAX请求,会发送undefined作为请求数据,导致控制器参数为null。

修正后的JS代码:

$('#uploadImage').on('click', function (e) {
    e.preventDefault();
    var fileInput = $('#profilePicture')[0];
    var file = fileInput.files[0];
    console.log(file);

    if (!file) {
        alert("Please Select File");       
        console.log(file);
        return; // 终止后续AJAX请求
    }
    
    var formData = new FormData();
    formData.append('profileImage', file);

    console.log(formData.get("profileImage"))

    $.ajax({
        url: '@Url.Action("UploadImage", "User")',
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        success: function (response) {
            if (response.flag) {
                toastr.success(response.message, "Success!");
            } else {
                toastr.error(response.message, "Error!");
            }
        },
        error: function (xhr, status, error) {
            alert("Some Issue Occurred Please Try Again");
            toastr.error("An error occurred while uploading the image.", "Error!");
        }
    });
});

3. 请求大小超出限制

ASP.NET Core默认限制了请求体大小(默认30MB),如果上传的图片超过这个限制,控制器会无法接收文件,参数为null。

解决方法:在Program.cs(.NET 6+)或Startup.cs(.NET 5及更早)中配置更大的请求限制:

// .NET 6+ Program.cs
builder.Services.Configure<FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = 104857600; // 设置为100MB
});

4. 空catch块隐藏错误

你的控制器代码中catch块是空的,无法排查上传过程中出现的异常(比如文件读取失败、Session获取失败等),建议添加日志或错误返回:

catch (Exception ex)
{
    // 可使用ILogger记录错误日志
    Response.Flag = false;
    Response.Message = "图片上传失败,请稍后重试";
    return Response;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 00:49:58