uploadFile method
This method uploads the file
endPoint
- Endpoint of the API
file
- the file which is to be uploaded
fileKey
- file will be posted under this key
data
- Map representation of data to be posted along with the file
isAuthenticated
- if the API is to be authenticated or not
Implementation
Future<Response> uploadFile(String endPoint, File file, String fileKey,
{Map<String, String>? data, bool isAuthenticated = true}) async {
assert(endPoint.isNotEmpty);
assert(fileKey.isNotEmpty);
/// Common header
var headers = {'Content-Type': 'application/json'};
/// if the API is to be authenticated, add a bearer token
if (isAuthenticated) {
headers.addAll({'Authorization': 'Bearer ${await _getToken()}'});
}
/// Create multipart request
final mimeTypeData =
lookupMimeType(file.path, headerBytes: [0xFF, 0xD8])!.split('/');
final multipartRequest =
http.MultipartRequest('POST', Uri.parse(baseUrl! + endPoint));
final _file = await http.MultipartFile.fromPath(fileKey, file.path,
contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
/// Add headers, files and fields to the multipart request
multipartRequest.headers.addAll(headers);
multipartRequest.files.add(_file);
if (data != null) multipartRequest.fields.addAll(data);
var response;
/// Send the request and await for the response
final streamedResponse = await multipartRequest.send();
response = await http.Response.fromStream(streamedResponse);
return _handleResponse(response);
}