我正在尝试创建一个发送图像文件和文本的http.post请求。我认为我只向服务器发送部分请求并被拒绝。我在MultiPartForm和下面的方法中尝试过这个
我试图创建post请求但是,我收到此错误:未处理的异常:类型'_File'不是类型转换中类型'String'的子类型
void createPreferences(
String phone,
String nickName,
String customerType,
double age,
File currentSelfie) {
//Variables
var uri = Uri.http('10.0.2.2:8000', '/api/customer/create_customer_details/', params);
var params = {
'access_token': _accessTkn,
};
final Map<dynamic, dynamic> custPreferences = {
'phone': phone,
'nick_name': nickName,
'customer_type': customerType,
'age': '${'age'}',
};
var request = http.MultipartRequest("POST", uri,);
var multipartFile = new http.MultipartFile('current_selfie', stream, length,
filename: basename(currentSelfie.path));
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
final Map<String, dynamic> responseData = json.decode(response.body);
print(responseData);
print('Response body: ${response.body}');
});
}
我想创建此请求并验证我的服务器是否接受了我的数据。
你可以做的是将你的文件(图像)转换为base64并将其作为字符串示例上传:
import 'dart:convert';
void createPreferences(
String phone,
String nickName,
String customerType,
double age,
File currentSelfie) {
//Variables
var url = 'http://10.0.2.2:8000/api/create_customer_details/?';
final Map<dynamic, dynamic> custPreferences = {
'phone': phone,
'nick_name': nickName,
'customer_type': customerType,
'age': '${'age'}',
'current_selfie': base64Encode(currentSelfie.readAsBytesSync()),
'access_token': _accessTkn,
};
http.post(url, body: custPreferences, headers: {
"Content-Type": "application/x-www-form-urlencoded"
}).then((http.Response response) {
print(response);
final Map<String, dynamic> responseData = json.decode(response.body);
print(responseData);
print('Response body: ${response.body}');
});
}
然后在您的服务器中解码它。