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

如何在Flutter Web应用中上传多个FilePicker文件?

多文件上传实现方案

首先确保你的pubspec.yaml中添加了http依赖(用于发送网络请求):

dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0
  file_picker: ^5.5.0 # 保持与你当前使用的版本一致

在代码文件顶部导入必要的包:

import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';

然后替换上传按钮的点击逻辑即可,核心是通过MultipartRequest构建表单数据(对应你PostMan里的form-data上传方式):

TextButton(
  onPressed: () async {
    if (FileList == null || FileList!.files.isEmpty) {
      print('请先选择要上传的文件');
      return;
    }

    // 替换为同事提供的实际API地址
    const uploadApiUrl = 'https://your-server-upload-api.com';

    for (final platformFile in FileList!.files) {
      try {
        // 创建POST类型的multipart请求
        final request = http.MultipartRequest('POST', Uri.parse(uploadApiUrl));
        
        // 添加文件字段(键名要和PostMan里的`file`完全一致)
        final uploadFile = await http.MultipartFile.fromPath(
          'file',
          platformFile.path!,
          contentType: MediaType('application', 'octet-stream'),
          filename: platformFile.name,
        );
        request.files.add(uploadFile);

        // 如果API需要请求头(比如token验证),可以在这里添加
        // request.headers['Authorization'] = 'Bearer your-auth-token';

        // 发送请求并处理响应
        final response = await request.send();
        final responseContent = await response.stream.bytesToString();

        if (response.statusCode == 200) {
          print('${platformFile.name} 上传成功: $responseContent');
        } else {
          print('${platformFile.name} 上传失败,状态码: ${response.statusCode},响应内容: $responseContent');
        }
      } catch (error) {
        print('${platformFile.name} 上传出错: $error');
      }
    }
  },
  child: Text('upload'),
)

关键注意事项:

  • 必须将uploadApiUrl替换为同事提供的真实上传接口地址
  • file字段名要和PostMan中配置的完全一致(从你的截图看就是file)
  • 如果API支持批量上传多个文件,也可以在同一个request.files中添加所有选中的MultipartFile,一次性发送请求(具体要看接口是否支持)
  • 若有额外的请求头要求(比如身份验证token),直接通过request.headers添加即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 09:20:21