uploadImage static method
Implementation
static Future<dynamic> uploadImage(String path, String url,
String serverImageName, String typeToken, String bearerToken) async {
try {
// Find the mime type of the selected file by looking at the header bytes of the file
final mimeTypeData =
lookupMimeType(path, headerBytes: [0xFF, 0xD8])?.split('/');
// Intilize the multipart request
final imageUploadRequest = http.MultipartRequest('POST', Uri.parse(url));
// Attach the file in the request
final file = await http.MultipartFile.fromPath(serverImageName, path,
contentType: MediaType(mimeTypeData![0], mimeTypeData[1]));
// Explicitly pass the extension of the image with request body
// Since image_picker has some bugs due which it mixes up
// image extension with file name like this filenamejpge
// Which creates some problem at the server side to manage
// or verify the file extension
// imageUploadRequest.fields['ext'] = mimeTypeData[1];
imageUploadRequest.fields['type'] = 'bvn';
imageUploadRequest.fields['token'] = typeToken;
imageUploadRequest.files.add(file);
imageUploadRequest.headers['content-type'] = 'application/json';
imageUploadRequest.headers['Authorization'] = 'Bearer $bearerToken}';
final streamedResponse = await imageUploadRequest.send();
final response = await http.Response.fromStream(streamedResponse);
// print('status code = ' + response.statusCode.toString());
// print('response body = ' + response.body.toString());
if (response.statusCode == 200) {
String data = response.body;
var decodedData = jsonDecode(data);
return decodedData;
} else {
return 'failed';
}
} catch (ex) {
throw Exception('No internet connectivity');
}
}