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

Flutter Web使用Appwrite存储文件报错:File bytes must be provided

解决Flutter Web下Appwrite Storage上传图片报错“File bytes must be provided for Flutter web”

问题根源

Flutter Web环境受浏览器安全机制限制,image_picker返回的XFile.path并非真实本地文件路径,InputFile.fromPath无法读取到文件内容,因此触发Appwrite的必填字节报错。

解决方案

改用InputFile.fromBytes,通过读取XFile的字节数据创建上传文件对象,具体步骤:

  • 读取选中图片的字节数据
  • 用InputFile.fromBytes构建上传所需实例
  • 调用storage.createFile完成上传

修改后的代码

Storage storage = Storage(client);

final image = await picker.pickImage(source: ImageSource.gallery);

if (image != null) {
  // 读取图片字节数据
  final imageBytes = await image.readAsBytes();
  
  var imageInput = InputFile.fromBytes(
    bytes: imageBytes,
    filename: image.name, // 使用XFile自带文件名,避免格式不匹配
  );

  try {
    var result = await storage.createFile(
      bucketId: bucketId,
      fileId: ID.unique(),
      file: imageInput,
    );
    // 上传成功后续逻辑
  } on AppwriteException catch (e) {
    print('上传失败: ${e.message}');
  } catch (e) {
    print('读取图片失败: $e');
  }
}

额外提示

  • 优先使用XFile.name作为上传文件名,避免手动指定导致的格式错误
  • 添加异常捕获,方便排查上传及读取过程中的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 09:06:00