我是Flutter的新手。我想上传图像和一些详细信息到我的API。我有关于"message": "Undefined variable: extension"
的错误。我的图片文件是普通图片文件,不是base64编码的图片。
这是我打开画廊的代码:
_openGallery(BuildContext context) async {
var picture = await ImagePicker.pickImage(source: ImageSource.gallery);
this.setState(() {
imageFile = picture;
Navigator.of(context).pop();
});
}
以下是上传的代码:
Future upload(BuildContext context) async {
try {
String url = Uri.encodeFull("https://API_URL");
http.Response response = await http.post(url,
body: {
'photo': imageFile.path,
'title': titleController.text,
'description': descriptionController.text,
}
);
print(response.body);
} catch(e) {
print(e);
}
}
如何解决此错误?
答案 0 :(得分:2)
尝试一下
Map<String, String> headers = { "Authorization": 'token'};
var request = http.MultipartRequest('POST', Uri.parse(url));
request.headers.addAll(headers);
request.files.add(http.MultipartFile.fromBytes('photo', imageFile.readAsBytesSync(), filename: 'photo.jpg'));
request.fields['title'] = titleController.text;
request.fields['description'] = descriptionController.text;
final response = await request.send();
final respStr = await response.stream.bytesToString();
print(respStr);