想要从图库或相机上传图像到API这里是我的图像API
Future profileImageUser(String user_id, String image) async {
String url = 'api';
final response = await http.post(Uri.parse(url),
body: {
'user_id': user_id,
'image': image
}
);
var convertedDataJson = jsonDecode(response.body);
return convertedDataJson;
}
这是我如何让用户id和图像上传通过rest api。
Future _imgFromCamera() async {
final image = await ImagePicker().pickImage(source: ImageSource.camera);
setState(() {
_image = image;
final bytes = File(_image!.path).readAsBytesSync();
String img64 = base64Encode(bytes);
print(img64);
});
SharedPreferences prefs = await SharedPreferences.getInstance();
if (_formKey.currentState!.validate()) {
var myId = prefs.getString('user_id');
print(myId);
var myProfile = _image;
print(myProfile);
var rsp = await profileImageUser(
myId.toString(),
myProfile.toString(),
);
print(rsp);
if (rsp['status'] == true) {
print(rsp);
} else {
print('failed');
}
}
当我从图库或相机上传图像时,它打印id和图像如下
I/flutter ( 6665): Instance of 'XFile'
I/flutter ( 6665): 111
,但它也显示以下错误
{status: 400, message: There is some trouble to proceed your action!, data: null}
这是我的邮差API参数
键:user_id值:76关键:形象值:data:image/jpeg;base64,(和其他数据)
任何解决方案。
我解决问题基本上我没有正确地转换形象64年基础这是你应该如何做
Future createAlbum(String user_id , File image) async {
final response = await http.post(
Uri.parse('api'),
/* headers: {
'Accept': 'multipart/form-data'
},*/
body: {
'user_id': user_id,
'image': selectedImage != null ? 'data:image/png;base64,' +
base64Encode(selectedImage!.readAsBytesSync()) : '',
},
);
final responseJson = await json.decode(json.encode(response.body));
print(responseJson);
}