.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;
});
 }
相关推荐
wocwin3 天前
uniapp微信小程序封装navbar组件
微信小程序·uni-app·vue3·组件封装·navbar
公子小六4 天前
ASP.NET Core WebApi+React UI开发入门详解
react.js·ui·c#·asp.net·.netcore
工藤新一OL4 天前
.netCore的winform程序如何调用webapi
c#·.net·.netcore·visual studio
江沉晚呤时5 天前
深入解析 C# 开闭原则(OCP):设计可扩展的系统
数据库·c#·系统安全·.netcore
留白声5 天前
uniapp主题切换功能,适配H5、小程序
前端·css·小程序·uni-app·vue3·主题切换
江沉晚呤时6 天前
深入解析外观模式(Facade Pattern)及其应用 C#
java·数据库·windows·后端·microsoft·c#·.netcore
江沉晚呤时7 天前
深入解析代理模式(Proxy Pattern):设计与应用
安全·c#·系统安全·.netcore
小吴同学·8 天前
NET6 WebApi第5讲:中间件(源码理解,俄罗斯套娃怎么来的?);Web 服务器 (Nginx / IIS / Kestrel)、WSL、SSL/TSL
中间件·c#·.net·.netcore·.net core
码农研究僧8 天前
uniapp的图片上传与提交(Demo记录)
uni-app·vue·图片上传·js
江沉晚呤时9 天前
深入解析组合模式(Composite Pattern):概念、结构与应用
java·开发语言·后端·c#·.netcore