Upload images to REST API with Flutter using Dio Package
After the overwhelming response of flutter developer on my story of upload images to REST API with flutter using http package, I have seen many people struggling to do that with dio package. Beginners usually want a descriptive and easy to learn material from where they can find a bit of code snippets to use.
In this story I will write on how to upload images from flutter to a REST API using dio package. I will try my best to explain every aspect of it but if you think something is missing or have a suggestion, please do comment and help me in my learning journey.
Lets Start with Adding the dio Package to your App.
Dio is powerful http client for dart and help you in my aspects while connecting to a server from your flutter app, e.g serialization & deserialization of response.
Run the Follow command in your project directory terminal:
$ dart pub add dio
For getting image from device Gallery or camera, I used the Image Picker package.
Run the Follow command in your project directory terminal:
$ flutter pub add image_picker
Here is the code to get Image from gallery.
Future<File> getImage() async {
final ImagePicker _picker = ImagePicker();
// Pick an image
final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
//TO convert Xfile into file
File file = File(image!.path);
//print(‘Image picked’);
return file;
}
Now we have Image picked from gallery. Import dio package in your dart file where MultipartRequest will be done as:
import 'package:dio/dio.dart';
Then Create FromData Object using fromMap named constructor in which I am going to Include My Image which I have to send over Rest API.
var formData = FormData.fromMap({
'file': await MultipartFile.fromFile(empFace.path, filename: empCode),
});
Here I included a file using key ‘file’ in Map. It returns us the FormData Object which we will use to send to server. We create a MultipartFile using the file of our camera image which we can use to send over the internet.
Finally send the request to REST API using dio like:
final response = await Dio().post(
'your Api url',
data: formData,
);
We passed the formData to post method and it will automatically handle the contentType for us. Usually we use form-data headers for sending images to server which are like:
headers: {
'Content-Type': 'multipart/form-data'
},
Using dio, we don’t need to specify our content-type in header.
Thats it, you can handle responce of API or catch errors as you want.
Complete code for better understanding of scenrio and use case is here:
Future<bool> registerEmployeeFace(
{required File empFace, required String empCode}) async {
final url =
'My API URL';
try {
var formData = FormData.fromMap({
'file': await MultipartFile.fromFile(empFace.path, filename: empCode),
});
final response = await Dio().post(
url,
data: formData,
);
if (response.statusCode == 200) {
var map = response.data as Map;
print('success');
if (map['status'] == 'Successfully registered') {
return true;
} else {
return false;
}
} else {
//BotToast is a package for toasts available on pub.dev
BotToast.showText(text: 'Error');
return false;
}
} on DioError catch (error) {
log(error.message);
throw YourException(error);
} catch (_) {
log(_.toString());
throw 'Something Went Wrong';
}
}
I hope its super easy for beginners to do this request and integrate complex APIs quickly. for More Github
If you find it helpful please give it a thumb and share it with your friends.