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
Uint8Listdirectly 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
fileBytesin 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.sizewill matchfileBytes.lengthexactly.- The Blob will be valid and work as expected in Web API calls like
putObject.
内容的提问来源于stack exchange,提问作者Xiaoshuyui
相关产品推荐
相关产品推荐

