我正在尝试创建一个http.post请求,该请求将图像文件与文本一起发送。我认为我只是向服务器发送了部分请求,服务器被拒绝了。我已经在MultiPartForm和下面的方法中尝试过
我尝试创建发布请求,但出现此错误:未处理的异常:类型'_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}');
});
}
我想创建此请求并验证我的服务器接受了我的数据。
答案 0 :(得分:1)
您可以做的是将文件(图像)转换为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}');
});
}
然后在您的服务器中对其进行解码。