Created
February 27, 2025 12:45
-
-
Save wildwind123/602be1fd34a90f9a44b78b0418ee424a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:js_interop'; | |
import 'dart:typed_data'; | |
import 'package:web/web.dart' as web; | |
void webOpenFilePicker( | |
Function(web.File f, Uint8List bytes) hookSuccess, | |
Function(String) hookError, | |
bool openFileInBrowser, | |
) { | |
final input = | |
web.HTMLInputElement() | |
..type = 'file' | |
..accept = '*/*'; // Accept all file types | |
input.click(); | |
input.onChange.listen((event) { | |
final files = input.files; | |
if (files != null && files.length > 0) { | |
final file = files.item(0)!; // Get the first file | |
final reader = web.FileReader(); | |
// Log file size for debugging | |
print("Selected file: ${file.name}, Size: ${file.size} bytes"); | |
// Set onload callback | |
reader.onload = | |
(web.Event event) { | |
if (reader.result != null) { | |
final arrayBuffer = reader.result as ByteBuffer; | |
final bytes = Uint8List.view(arrayBuffer); | |
if (openFileInBrowser) { | |
// Try to open the file in a new tab | |
final url = web.URL.createObjectURL(file); | |
final opened = web.window.open(url, '_blank'); | |
if (opened == null) { | |
_forceDownload(file, url); | |
} | |
} | |
hookSuccess(file, bytes); | |
} else { | |
hookError('reader.result is null'); | |
} | |
}.toJS; | |
// Set onerror callback with better diagnostics | |
reader.onerror = | |
(web.Event error) { | |
hookError( | |
"Error details: ${reader.error?.toString() ?? 'No details'}", | |
); | |
}.toJS; | |
// Start reading the file as ArrayBuffer | |
reader.readAsArrayBuffer(file); | |
} | |
}); | |
} | |
// Fallback to force download if opening fails | |
void _forceDownload(web.File file, String url) { | |
final anchor = | |
web.HTMLAnchorElement() | |
..href = url | |
..download = file.name | |
..click(); | |
web.URL.revokeObjectURL(url); // Clean up | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment