I'm trying to post an image to API. This is my Post Function:
Future<http.Response> ajoutProduit(
String refProduit,
String nomProduit,
double prixAchatProduit,
double prixVenteProduit,
String descriptionProduit,
File imageProduit) async {
List produits = [];
final response = await http.post(
Uri.parse('http://127.0.0.1:8000/api/produit/'),
headers: <String, String>{'Content-Type': 'multipart/form-data'},
body: jsonEncode(<String, dynamic>{
'refProd': refProduit,
'nomProd': nomProduit,
'prixAchat': prixAchatProduit,
'prixVente': prixVenteProduit,
'descriptionProd': descriptionProduit,
'imageProd': imageProduit,
}),
);
if (response.statusCode == 200) {
return produits = jsonDecode(response.body);
} else {
throw Exception('Erreur base de données!');
}
}
and this is my ImagePicker function:
File uploadimage;
Future<void> chooseImage() async {
final ImagePicker picker = ImagePicker();
var choosedimage = await picker.pickImage(source: ImageSource.gallery);
final File convertimage = await File(choosedimage.path);
setState(() {
uploadimage = convertimage;
});
} Finally, this is the confirm button:
ElevatedButton(
onPressed: (() {
if (_formKey.currentState.validate()) {
setState(() {
future = ajoutProduit(
refProduit.text,
nomProduit.text,
double.parse(prixAchatProduit.text),
double.parse(prixVenteProduit.text),
descriptionProduit.text,
uploadimage);
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Produit Ajouté')),
);
Navigator.of(context, rootNavigator: true).pop();
}
}), ...
When i press the button i get this error in the debug console: Error: Converting object to an encodable object failed: Instance of '_File'
I would suggest uploading the file as form you can do something like the following
List<http.MultipartFile> files = [await http.MultipartFile.fromPath('file', file.path)];
http.MultipartRequest request = new http.MultipartRequest("POST", uri);
for (http.MultipartFile file in files) {
request.files.add(file);
}
http.StreamedResponse responseStream = await request.send();
http.Response response = await
http.Response.fromStream(responseStream).timeout(Duration(seconds: timeoutSeconds));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.