downloadMedia method
Common function to download media from pixabay cdn remember pixabay.com does not prefer hotlinking
Implementation
Future<BytesBuilder> downloadMedia(PixabayMedia media, String res,
[Function? callback]) async {
var completer = Completer<BytesBuilder>();
HttpClient httpClient = HttpClient();
String downloadUrl = media.getDownloadLink(res: res)!;
print("Downloading $downloadUrl");
HttpClientRequest request = await httpClient.getUrl(Uri.parse(downloadUrl));
HttpClientResponse response = await request.close();
// Process the response.
if (response.statusCode == 200) {
// response: OK
int fileSize = response.contentLength;
int downloaded = 0;
// store on file system?
// String dir = (await getApplicationDocumentsDirectory()).path;
//response.pipe(File('$dir/${image.getId()}.jpg').openWrite());
var contents = BytesBuilder();
_downloadStreamSub = response.listen((List<int> data) {
downloaded += data.length;
contents.add(data);
// handle data
double progress = downloaded / fileSize;
if (callback != null) callback(progress);
progressStreamController.add(progress);
}, onDone: () {
_downloadStreamSub = null;
progressStreamController = StreamController.broadcast(onCancel: () {
_downloadStreamSub?.cancel();
});
completer.complete(contents);
});
} else {
// something went wrong :(
completer.completeError("Http error: ${response.statusCode}");
print("Http error: ${response.statusCode}");
}
return completer.future;
}