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

Flutter选取图库图片上传报错Cannot extract a file path from a blob如何解决

错误根因

你当前运行的是Flutter Web平台,image_picker插件在Web环境下返回的XFile路径为Blob协议URI,不属于本地文件系统路径,无法通过File.fromUri直接解析读取内容,因此抛出该错误。

修复步骤

  • 不要通过路径构造File对象读取字节,直接使用XFile自带的跨平台读取API,自动适配Web/移动端差异
  • 修复原有代码中Uri.parse("IMAGE_UPLOAD_URL")的语法错误:你把变量名写进了字符串常量里,导致实际请求地址错误
  • 补全缺失的错误打印逻辑,添加上传成功后UUID的读取逻辑

注意事项

使用MediaType需要先导入依赖:import 'package:http_parser/http_parser.dart';,如果项目没引入可以直接省略contentType参数,大部分后端会自动识别文件类型。

修复后代码

调整选图逻辑(推荐)

直接存储XFile实例,减少后续路径解析成本:

XFile? _pickedImage; // 替换原来的字符串类型的_imgPath变量

pickImage() async {
  XFile? result;
  try {
    result = await ImagePicker().pickImage(
      source: ImageSource.gallery,
      imageQuality: 70,
      maxWidth: 1024,
    );
  } on PlatformException {
    Get.snackbar('', 'Cannot access gallery...');
  }

  if (result != null) {
    setState(() {
      _pickedImage = result;
    });
  }
}

修复后的上传方法

uploadImage(XFile imageFile) async {
  const IMAGE_UPLOAD_URL = 'http://localhost:1234/simpleApi/image/upload';
  final postUri = Uri.parse(IMAGE_UPLOAD_URL);
  final request = http.MultipartRequest("POST", postUri);
  // 直接调用XFile的跨平台读字节方法,自动兼容Web端Blob URI
  request.files.add(http.MultipartFile.fromBytes(
    'file',
    await imageFile.readAsBytes(),
    filename: imageFile.name,
    contentType: MediaType('image', 'jpeg'),
  ));

  try {
    final response = await request.send();
    if (response.statusCode == 200) {
      // 读取接口返回的UUID
      final uuid = await response.stream.bytesToString();
      print("Upload OK, returned UUID: $uuid");
    } else {
      print("Upload failed, status code: ${response.statusCode}");
    }
  } catch (e) {
    print("Upload error: $e");
  }
}

调用示例

选图完成后直接传入XFile实例即可触发上传:

if (_pickedImage != null) {
  uploadImage(_pickedImage!);
}

如果你必须保留传路径的原有写法,也可以在上传时通过路径构造XFile实例:

uploadImage(String pathToFile) async {
  final imageFile = XFile(pathToFile);
  // 后续逻辑和上面的上传方法完全一致
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:39:03