.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;
});
 }
相关推荐
时光追逐者13 小时前
C#/.NET/.NET Core学习路线集合,学习不迷路!
开发语言·学习·c#·asp.net·.net·.netcore·微软技术
Jeffrey侠客1 天前
.Net Core 6.0 WebApi在Centos中部署
linux·centos·.netcore
CherishTaoTao1 天前
Vue3 keep-alive核心源码的解析
前端·vue3
技术拾荒者2 天前
.net core mvc 控制器中页面跳转
后端·c#·asp.net·mvc·.netcore
时光追逐者2 天前
Visual Studio 2022:一个功能全面且强大的IDE
ide·c#·.net·.netcore·visual studio
虞泽3 天前
鸢尾博客项目开源
java·spring boot·vue·vue3·博客
前端杂货铺4 天前
简记Vue3(三)—— ref、props、生命周期、hooks
vue.js·vue3
.Net Core 爱好者4 天前
ASP .NET CORE 6 在项目中集成WatchDog开源项目
c#·.net·.netcore
静谧的美4 天前
vue3-element-admin 去掉登录
vue.js·前端框架·vue3·去掉登录