【发布时间】:2020-01-01 01:52:11
【问题描述】:
我在我的应用程序中创建了一个表单,但图像字段没有将任何图像解析到服务器。我使用画廊中的图像选择器。 这是我从图库中获取图片的代码:
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 具有相同的作用?然后,当我运行此代码时,我不知道为什么,但图像未上传。我该如何解决这个问题?
【问题讨论】:
-
你能告诉我们你的
newPost()函数吗? -
我已经用 newPost 方法更新了我的问题,希望你能帮我解决这个问题。谢谢你:)
-
我想你尝试上传图片文件名,而不是图片,请阅读stackoverflow.com/questions/44841729/…
-
您使用的是什么类型的数据库?您从图库中获取的图像文件是一个 blob 文件,您是否要保存整个文件?
标签: image api file-upload flutter