I am working on a Flutter application, and I need to download a ZIP file from a public server using an HTTP GET request. The URL is something like: “https://example.com/file.zip”.
However, when I try to download the file from the web version of my app, the browser blocks the request due to CORS (Cross-Origin Resource Sharing) restrictions. The server does not include the Access-Control-Allow-Origin header in its response.
Here’s the basic structure of my current code:
import 'package:http/http.dart' as http;
import 'dart:html' as html;
// import 'dart:io';
Future<void> downloadZipFileWidget() async {
const String url = 'https://example/file.zip';
const String savePath = 'file.zip';
try {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final fileBytes = response.bodyBytes;
print('File downloaded successfully');
createDownloadLink(fileBytes, savePath);
print('File saved to $savePath');
} else {
print('Error: ${response.statusCode}');
}
} catch (e) {
print('Error: $e');
}
}
void createDownloadLink(List<int> bytes, String fileName) {
final blob = html.Blob([bytes]);
final url = html.Url.createObjectUrlFromBlob(blob);
final anchor = html.AnchorElement(href: url)
..target = 'blank'
..download = fileName
..click();
html.Url.revokeObjectUrl(url);
}
And I call to the function from another “.dart” file.
when running on the web, I encounter the CORS issue.
Question:
What are the best ways to bypass CORS restrictions for downloading files in a Flutter Web app?
Are there proxy services, or should I implement my own proxy server?
Is there any way to work directly with the server without needing CORS modifications?
1