Flutter web : file_picker : Not working on Safari

133 Views Asked by At

I have implemented file_picker in my Flutter web app for uploading files. It works fine on Chrome but not on Safari. On Safari, the file picker does not show.

Here is my code:

Future<void> uploadFile(String uploadUrl, {int maxBytes = 2097152}) async {


FilePickerResult? result = await FilePicker.platform.pickFiles(); //type: FileType.image
if (result == null) {
  LogManager().log('No file selected.');
  return;
}

final bytes = result.files.first.bytes;
if (bytes == null) return;

LogManager().log('File size: ${bytes.length}');
if (bytes.length > maxBytes) {
  throw Exception('File size is too large.');
}

final uri = Uri.parse(uploadUrl);

try {
  Map<String, String> headers = {
    'Content-Length': '${bytes.length}',
  };
  await http.put(uri, headers: headers, body: bytes);

} on http.ClientException catch (e) {
  LogManager().log('uploadFile ClientException: $e');

} catch (e) {

  LogManager().log('uploadFile Unhandled exception: $e');

}

LogManager().log('WEB - Image uploaded successfully.');
}

Any ideas on what I am doing wrong ?

1

There are 1 best solutions below

0
Zigglzworth On

For anyone who encounters a similar issue. The problem was that I was not launching the file picker directly in the function called by the button tap that launches it. Rather I was doing so in a secondary function which works fine in Chrome but not in Safari. Moving the code:

FilePickerResult? result = await FilePicker.platform.pickFiles();

To the function directly called by the button tap fixed the problem.