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

Flutter发起POST请求时出现413 Request Entity Too Large错误求助

Flutter上传图片报413 Request Entity Too Large但Postman正常的解决方案

问题重现

我在Flutter中发起多文件上传的POST请求时收到413 Request Entity Too Large错误,但使用Postman发起相同请求却能成功返回200 OK。Flutter代码如下:

uploadImage() async {
    print('inside uploadimage function');
    
    WidgetsBinding.instance.addPostFrameCallback((_) => setState((){isLoading = true;}  ));
    final request = http.MultipartRequest(
      "POST", Uri.parse('http://server/upload'));
    final headers = {"Content-type":"multipart/form-data"};
    request.files.add( http.MultipartFile('image1',
    widget.imagefile1!.readAsBytes().asStream(),widget.imagefile1!.lengthSync(),
    filename: widget.imagefile1!.path.split("/").last));
   
    request.files.add(http.MultipartFile('image2',
    imageFile!.readAsBytes().asStream(),imageFile!.lengthSync(),
    filename: imageFile!.path.split("/").last));
    request.headers.addAll(headers);

    final response = await request.send();
    http.Response res = await http.Response.fromStream(response);
    print('statuscode:');
    print(response.statusCode);
    print(response.reasonPhrase);    
  }

核心原因分析

  1. 手动设置Content-Type头冲突:http.MultipartRequest会自动生成正确的multipart/form-data请求头(包含自动生成的boundary分隔符),手动添加的{"Content-type":"multipart/form-data"}会覆盖或干扰自动生成的头,导致服务器无法正确解析请求体,进而误判请求实体大小。
  2. 文件流读取方式低效:使用readAsBytes().asStream()会先将整个文件加载到内存再转为流,对于大图片来说不仅占用内存,还可能导致传输的数据流格式与Postman的请求存在差异。

解决方案

1. 移除手动添加的Content-Type头

删除request.headers.addAll(headers);这一行,让MultipartRequest自动生成正确的请求头。修改后的代码:

uploadImage() async {
    print('inside uploadimage function');
    
    WidgetsBinding.instance.addPostFrameCallback((_) => setState((){isLoading = true;}));
    final request = http.MultipartRequest(
      "POST", Uri.parse('http://server/upload'));
    
    // 移除手动设置的Content-Type头
    request.files.add(http.MultipartFile('image1',
      widget.imagefile1!.openRead(), widget.imagefile1!.lengthSync(),
      filename: widget.imagefile1!.path.split("/").last));
   
    request.files.add(http.MultipartFile('image2',
      imageFile!.openRead(), imageFile!.lengthSync(),
      filename: imageFile!.path.split("/").last));

    final response = await request.send();
    http.Response res = await http.Response.fromStream(response);
    print('statuscode:');
    print(response.statusCode);
    print(response.reasonPhrase);    
  }

2. 使用高效的文件流读取方式

将readAsBytes().asStream()替换为openRead(),直接从文件系统读取流,避免将整个文件加载到内存,同时保证数据流格式更接近Postman的请求。

3. 额外排查点

  • 确认Flutter中上传的文件与Postman中使用的是同一文件,避免因文件实际大小不同导致的错误。
  • 调试请求头:打印request.headers查看实际发送的请求头,对比Postman的请求头,确认是否存在其他差异。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:06:23