Я боролся в течение нескольких дней, пытаясь заставить эту вещь работать.Этот метод POST предназначен для загрузки изображения, которое должно быть «Файл» и подпись.API требует:
PAYLOAD:
- caption
- image
HEADER
- AUTHENTICATION
Я новичок в трепетании, и я прошел много уроков, но, похоже, ничего не получается.
вот мой код:
static Future<void> addPost(
BuildContext context, String caption, File image) async {
debugPrint("$image");
String imageFile = image.path.split("/").last;
debugPrint("$imageFile");
Utils().showRegisterProgressDialog(context);
final userData = {
"caption": caption,
"image" : image
};
final response = await http.post(
APIServices.HTTP_DOMAIN + APIServices.POST_ADD_NEW,
body: userData,
headers: {"Authentication": "Bearer " + Constants.token});
debugPrint("STATUS: ${response.statusCode}");
if (response.statusCode == 200) {
Utils().hidePostingDialog(context);
Utils().postSuccessDialog(context);
} else {
Utils().hidePostingDialog(context);
Utils().postErrorDialog(context);
}
print(response.body);
return response;
}
Буду признателен за любую помощь и предложения.
РЕДАКТИРОВАТЬ
Я также пытался использовать MultipartRequest
, но он возвращает код состояния 500
вот мой код:
static Future<void> addPost(
BuildContext context, String caption, File image) async {
Map<String, String> headers = {
"Authentication": "Bearer ${Constants.token}"
};
debugPrint("TOKEN : $headers");
Utils().showPostingDialog(context);
var stream = new http.ByteStream(DelegatingStream.typed(image.openRead()));
var length = await image.length();
var url =
Uri.parse("${APIServices.HTTP_DOMAIN}${APIServices.POST_ADD_NEW}");
debugPrint("TOKEN : $stream");
debugPrint("TOKEN : $length");
debugPrint("TOKEN : $url");
final request = http.MultipartRequest("POST", url);
debugPrint("TOKEN : $request");
debugPrint("TOKEN : $image");
debugPrint("TOKEN : ${image.path}");
var multipartFile =
new http.MultipartFile('file', stream, length, filename: image.path);
debugPrint("TOKEN : ${multipartFile.contentType}");
request.fields['caption'] = caption;
request.headers.addAll(headers);
request.files.add(multipartFile);
var response = await request.send();
debugPrint("TOKEN : ${response.request}");
print(response.statusCode);
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}