getWebPrediction method
- File imageFile
Gets a web-based prediction for a mosquito image.
Sends the image to a remote prediction service for classification. This provides an alternative to local model classification.
imageFile The image file to get prediction for.
Returns a WebPredictionResult with prediction data.
Throws an exception if the web request fails.
Implementation
Future<WebPredictionResult> getWebPrediction(File imageFile) async {
final url = Uri.parse(_mosquitoPredictionUrl);
var request = http.MultipartRequest('POST', url);
// 1. Detect the file's MIME type from its name
final mimeType = lookupMimeType(imageFile.path, headerBytes: [0xFF, 0xD8]);
print("Detected MIME type: $mimeType");
// 2. Create a MultipartFile with the correct Content-Type
final multipartFile = await http.MultipartFile.fromPath(
'file', // This is the field name the backend expects
imageFile.path,
// Use the detected MIME type. Fallback to a default if not found.
contentType: MediaType.parse(mimeType ?? 'image/jpeg'),
);
// 3. Add the correctly typed file to the request
request.files.add(multipartFile);
final streamedResponse = await _httpClient.send(request);
final response = await http.Response.fromStream(streamedResponse);
if (response.statusCode == 200) {
return WebPredictionResult.fromJson(json.decode(response.body));
} else {
throw Exception(
'Failed to get web prediction. Status: ${response.statusCode}, Body: ${response.body}');
}
}