.NetCore+vue3上传图片 Multipart body length limit 16384 exceeded.

实现目标。点击图片上传头像

效果图

前端部分图片上传关键代码

csharp 复制代码
<div class="avatar-wrap">
            <el-image
              style="width: 154px; height: 154px"
              :src="form.headPic"
              :fit="fit"
            />
          </div>
          <div class="upload-box">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :http-request="customUpload"
            >
              <!-- 自定义上传按钮 -->
              <div class="custom-upload-btn">
                <span>更换头像</span>
              </div>
            </el-upload>
          </div>

上传js部分

csharp 复制代码
<script>
import { ref, reactive, onMounted } from "vue";
import { uploadAvatar } from "../../api/auth";
import { ElMessage } from "element-plus";
export default {
  setup() {
    const fit = ref("cover");
    const form = reactive({
      userId: 0,
      headPic:
        "https://ww1.sinaimg.cn/mw690/9516662fgy1hct88xfrd9j20k00k0dho.jpg",
      userName: "",
      phone: "",
    });
    // 上传成功后的处理函数
    const handleAvatarSuccess = (response, file) => {
     
    };
    // 上传之前的检查函数
    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    };

    const customUpload = async (options) => {
      const { file, onSuccess, onError } = options;
      const formData = new FormData();
      formData.append("file", file);
      try {
        const response = await uploadAvatar(formData);
        onSuccess(response.data); // 上传成功时的回调
      } catch (error) {
        onError(error); // 上传失败时的回调
        ElMessage.error("上传失败,请重试");
      }
    };
    return {
      fit,
      form,
      customUpload,
      beforeAvatarUpload,
      handleAvatarSuccess,
    };
  },
};

auth.js

csharp 复制代码
//头像上传
export function uploadAvatar(info) {
  return request({
    url: "/Pictrue/TestForm",
    headers: {
      "Content-Type": "multipart/form-data",
    },
    method: "post",
    data: info,
  });
}

有问题的后台【接口本身没有问题,小程序上传也使用的这个接口不会有问题】

csharp 复制代码
 public async Task<Result> PicUploadToUrl()
 {
     try
     {
         var files = Request.Form.Files;
         if (files.Count > 0)
         {
             List<string> urlList = new List<string>();
             foreach (var item in files)
             {
                 string[] arr = item.FileName.Split('.');              //得到当前的图片对象
                 string format = arr[arr.Length - 1];           //得到图片后缀名称
                 var rst = await pictureService.PicUploadToUrl(item.OpenReadStream(), item.FileName, format);
                 if (rst.IsSuccess)
                     urlList.Add(rst.Message);
                 else
                     return rst;
             }
             GC.Collect();
             return Result.NewSuccess(urlList);
         }
         return Result.NewError(message: "图片上传失败");
     }
     catch (Exception ex)
     {
         NLogUtil.Default.Log(LogLevel.Error, "PicUploadToUrl.上传错误:" + ex.Message);
         return Result.NewError(message: "图片上传失败");
     }
 }

解决办法,改变接收的方式

csharp 复制代码
[HttpPost]
[DisableRequestSizeLimit]
public async Task<Result> TestForm([FromForm] IFormCollection formData)
{
    try
    {
        var files = formData.Files;
        if (files.Count > 0)
        {
            List<string> urlList = new List<string>();
            foreach (var item in files)
            {
                string[] arr = item.FileName.Split('.');              //得到当前的图片对象
                string format = arr[arr.Length - 1];           //得到图片后缀名称
                var rst = await pictureService.PicUploadToUrl(item.OpenReadStream(), item.FileName, format);
                if (rst.IsSuccess)
                    urlList.Add(rst.Message);
                else
                    return rst;
            }
            GC.Collect();
            return Result.NewSuccess(urlList);
        }
        return Result.NewError(message: "图片上传失败");
    }
    catch (Exception ex)
    {
        NLogUtil.Default.Log(LogLevel.Error, "PicUploadToUrl.上传错误:" + ex.Message);
        return Result.NewError(message: "图片上传失败");
    }
}

注意startup.cs中的配置。这里根据实际情况进行配置需要的即可

csharp 复制代码
 public void ConfigureServices(IServiceCollection services)
 {
 //设置接收文件长度的最大值。
services.Configure<FormOptions>(x =>
{
    x.ValueLengthLimit = int.MaxValue;
    x.ValueCountLimit = int.MaxValue;
    x.MultipartBodyLengthLimit = int.MaxValue;//2147483647;
    x.MultipartHeadersCountLimit = int.MaxValue;
    x.MultipartBoundaryLengthLimit = int.MaxValue;
    x.BufferBodyLengthLimit = long.MaxValue;
    x.BufferBody = true;
    x.KeyLengthLimit = int.MaxValue;
    x.MultipartHeadersLengthLimit = int.MaxValue;
});
 }
相关推荐
Jinuss7 小时前
Vue3源码reactivity响应式篇之reactive响应式对象的track与trigger
前端·vue3
Jinuss14 小时前
Vue3源码reactivity响应式篇之EffectScope
前端·vue3
somethingGoWay21 小时前
wpf .netcore 导出docx文件
wpf·.netcore
somethingGoWay1 天前
wpf .netcore 导出pdf文件
pdf·wpf·.netcore
切糕师学AI2 天前
如何建立针对 .NET Core web 程序的线程池的长期监控
java·前端·.netcore
叫我阿柒啊3 天前
从Java全栈到前端框架的全面实战:一次真实面试的深度解析
java·spring boot·缓存·微服务·消息队列·vue3·rest api
csdn_aspnet3 天前
使用 MongoDB.Driver 在 C# .NETCore 中实现 Mongo DB 过滤器
mongodb·c#·.netcore
叫我阿柒啊3 天前
从Java全栈到Vue3实战:一次真实面试中的技术探索
java·数据库·spring boot·微服务·typescript·vue3·restful
tiancao2223 天前
安装3DS MAX 2026后,无法运行,提示缺少.net core的解决方案
.net·.netcore·3dsmax
csdn_aspnet3 天前
使用 C# .NETCore 实现MongoDB
mongodb·c#·.netcore