image - 我无法将图像文件上传到服务器(Flutter-API)
问题描述
我在我的应用程序中制作了一个表单,但图像字段没有将任何图像解析到服务器。我使用画廊中的图像选择器。这是我从画廊获取图像代码:
Future getImageFromGallery() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = image;
});
}
这是我的身体应用程序代码,带有来自画廊的文本字段和图像选择器:
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: new TextFormField(
maxLines: 3,
decoration: new InputDecoration(
labelText: "Keterangan"),
onSaved: (String val) => description = val,
),
),
Padding(
padding: const EdgeInsets.all(15.0),
child: SizedBox(
width: 100.0,
height: 100.0,
child: RaisedButton(
child: _image == null
? Icon(Icons.add_a_photo)
: Image.file(_image),
onPressed: () {
this.getImageFromGallery();
},
),
),
),
Padding(
padding: const EdgeInsets.only(top: 40.0),
child: RaisedButton(
child: Text("Submit"),
color: Colors.blue,
onPressed: () {
newPost();
},
这是我的 newPost 方法:
void newPost() async {
Map data = {
"destination": destination,
"start": start,
"finish": finish,
"person": person,
"route": route,
"descrption": description,
"image": image
};
var body = json.encode(data);
String token = await getToken();
var response = await http.post('https://api-wisapedia.herokuapp.com/posts/',
headers: {HttpHeaders.authorizationHeader: 'Bearer $token'},
body: body);
_newPostResponse =
NewPostResponse.fromJson(json.decode(response.body.toString()));
if (token != null) {
if (destination.isEmpty ||
start.isEmpty ||
finish.isEmpty ||
person.isEmpty ||
route.isEmpty ||
description.isEmpty ||
image.isEmpty) {
showDialog(
builder: (context) => AlertDialog(
content: Text('Please fill the form'),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('OK'),
)
],
),
context: context);
} else {
_formkey.currentState.save();
Navigator.push(
context, MaterialPageRoute(builder: (context) => MainScreen()));
}
} else {
showDialog(
builder: (context) => AlertDialog(
content: Text('You need to authenticate'),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('$token'),
)
],
),
context: context);
}
}
文本字段中有onSaved
方法使该字段的值可以通过API上传,但没有onSaved
图像方法。我很困惑是否: Image.file(_image)
具有相同的作用onSaved
?然后,当我运行此代码时,我不知道为什么,但图像未上传。我怎么解决这个问题?
解决方案
我认为你应该等待你的函数,因为它返回一个 Future。像这样的东西:
onPressed: () async {
await this.getImageFromGallery();
},
推荐阅读
- java - 如何将 Array1[][] 中不存在于 Array2[][] 中的新行添加/追加到 Java 中的 Array2[][]?
- c# - 使用 .net 比较字符串在验证表单中是否有效
- design-patterns - 如果微服务架构中的数据量很大,我应该复制数据吗?
- mongodb - 猫鼬查找和更新删除其他字段
- linux - 无法在 ubuntu 的 Visual Studio 代码中输入越南语
- python - ValueError:操作数无法与形状一起广播 (1,55) (42,)
- spring - Spring ouath2Authserver oauth/token 为授予 client_credentials 返回内部服务器错误
- cypress - cypress 是否会支持 Edge Html 浏览器
- html - Bootstrap 下拉菜单未显示在选框内
- python - Pandas 数据框通过绝对值优化获得最大值和最小值