How can I send image to API in string format? This is the code where the data is sent in MultipartFile instance but data['avatar']
accepts string. So how can I do it? Please help me with this.
static Future<Response> updateUserAccount({
XFile? avatar,
String? fullName,
String? email,
String? oldPhone,
String? phone,
String? city,
String? streetName,
String? landmark,
String? oldPassword,
String? password,
}) async {
final dio = Dio();
String token = await SecureStorageUtils.getToken();
dio.options.headers['accept'] = '*/*';
dio.options.headers['content-type'] = 'multipart/form-data';
dio.options.headers['authorization'] = 'Bearer $token';
Map<String, dynamic> data = {};
if (avatar != null) {
data['avatar'] = await MultipartFile.fromFile(avatar.path);
}
if (email != null) {
data['email'] = email;
}
if (oldPhone != null) {
data['old_phone_number'] = oldPhone;
}
if (phone != null) {
data['phone_number'] = phone;
}
if (city != null || streetName != null || landmark != null) {
final address = {};
if (city != null) {
address['city'] = city;
}
if (streetName != null) {
address['street_name'] = streetName;
}
if (landmark != null) {
address['landmark'] = landmark;
}
data['address'] = address;
}
if (oldPassword != null) {
data['old_password'] = oldPassword;
}
if (password != null) {
data['password'] = password;
}
if (fullName != null) {
data['full_name'] = fullName;
}
print("data: $data");
FormData formData = FormData.fromMap(data);
final response = await dio.patch(
AppUrl.currentUser,
data: formData,
);
return response;
}
I tried this way using base64Encoding but it did not work.
List<int> fileBytes = await avatar.readAsBytes();
String base64Avatar = base64Encode(fileBytes);
data['avatar'] = base64Avatar;
At my case is that i can send json data as the data is string file so i created a class that create base64 e.g.
class ToImageData {
static String imagetoData(String? imagepath) {
final extension = path.extension(
imagepath!.substring(imagepath.lastIndexOf("/")).replaceAll("/", ""),
);
final bytes = File(imagepath).readAsBytesSync();
String base64 =
"data:image/${extension.replaceAll(".", "")};base64,${base64Encode(bytes)}";
return base64;
}
}
so whenever i have to send file in json for i call it like this
// Lets make an example
final data = {
"avatar": ToImageData.imagetoData(file.path);
// result is like this data:image/png;base64,TEWUFDBSJWEH1232347GHSD
//something long text
}
final response = await dio.patch(
AppUrl.currentUser,
data: data ,
);
return response;
I hope this finds you helpful.