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

Flutter Web中Blob使用问题:图片转Blob后大小不符且无法使用

Solution for Blob Size Mismatch in Flutter Web FilePicker

Issue Breakdown

Two critical mistakes are causing your Blob to behave incorrectly:

  • Incorrect Blob initialization: Passing the Uint8List directly to the Blob constructor treats each byte as a separate string component, triggering unnecessary encoding that inflates the Blob size.
  • Wrong MIME type: Using "text/plain" for an image file corrupts the Blob's data structure, making it unusable for image-related operations.

Fixed Code

FilePickerResult? result = await FilePicker.platform.pickFiles(
  withData: true, // Ensure file bytes are loaded
);
if (result != null) {
  Uint8List? fileBytes = result.files.first.bytes;
  String fileName = result.files.first.name;
  // Use the file's native MIME type, fall back to extension-based guess if needed
  String? mimeType = result.files.first.mimeType ?? 
      (result.files.first.extension?.toLowerCase() == 'png' ? 'image/png' : 'image/jpeg');

  debugPrint(fileName);

  if (fileBytes != null && mimeType != null) {
    print(fileBytes.length);
    // Wrap Uint8List in a list and use correct MIME type
    Blob blob = Blob([fileBytes], mimeType);
    print(blob.size); // Now matches fileBytes.length
    await js.context.callMethod(
        'putObject', ["exampledir/exampleobject.png", blob, {}]);
  }
} else {
  // User canceled the picker
}

Key Fixes Explained

  • Blob Constructor Correction: Wrap fileBytes in a list ([fileBytes]). The Blob constructor expects an iterable of data parts; passing the raw Uint8List directly splits it into individual byte strings, leading to incorrect encoding and size discrepancies.
  • Proper MIME Type: Use the file's native MIME type (available via result.files.first.mimeType) or a fallback based on the file extension. This ensures the Blob retains the correct data structure for image files.
  • Remove Unnecessary Parameter: The third 'native' parameter in your original Blob call is for text line ending handling and has no place in binary image data creation.

Verification

After applying these changes:

  • blob.size will match fileBytes.length exactly.
  • The Blob will be valid and work as expected in Web API calls like putObject.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:20:41