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;
2
Answers
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.
so whenever i have to send file in json for i call it like this
I hope this finds you helpful.
For this I have used image_picker and image
import ‘package:image/image.dart’ as img;
import ‘package:image_picker/image_picker.dart’;