如何将图片以字符串格式发送给API?这是在MultipartFile示例中发送数据但data['avatar']
接受字符串的代码。那我该怎么做呢?请帮我拿这个。
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;
}
字符串
我试过使用base64Encoding的方法,但它没有工作。
List<int> fileBytes = await avatar.readAsBytes();
String base64Avatar = base64Encode(fileBytes);
data['avatar'] = base64Avatar;
型
2条答案
按热度按时间wfsdck301#
在我的情况是,我可以发送JSON数据,因为数据是字符串文件,所以我创建了一个类,创建base64,例如。
字符串
因此,每当我必须用JSON发送文件时,我会这样调用它
型
我希望这对你有帮助。
yks3o0rb2#
为此,我使用了image_picker和image
import 'package:image/image.dart' as img;
import 'package:image_picker/image_picker. dart';
字符串