Json 将表单数据发布到服务器
我在向服务器发送Json 将表单数据发布到服务器,json,flutter,post,form-data,Json,Flutter,Post,Form Data,我在向服务器发送post请求时遇到了很多问题。它需要表单数据类型 这是我输入后得到的错误 `image: [The image must be an image.]}} 除了用户从库中选择的int和文件图像之外,我的大多数数据都是字符串 这是我的代码: 省道代码 if(_image!=null){ setState(() { _isLoading = true; }); SharedPreferences sharedPreferen
post
请求时遇到了很多问题。它需要表单数据
类型
这是我输入后得到的错误
`image: [The image must be an image.]}}
除了用户从库中选择的int
和文件图像
之外,我的大多数数据都是字符串
这是我的代码:
省道代码
if(_image!=null){
setState(() {
_isLoading = true;
});
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var uri = NetworkUtils.host +
AuthUtils.updateSessionRequest;
Map<String, String> data = {"_method": "PATCH",
"first_name": widget.first_name,
"last_name": widget.last_name,
"phone": widget.phone,
"industry":widget.industry,
"country": widget.country,
"state": widget.state,
"fav_quote": widget.fav_quote,
"bio_interest": widget.bio_text,
"terms": "1",
"company": widget.company,
"position": widget.job_position,
"linked_in":widget.linkedin_profile,
"institution": widget.institution,
"degree": widget.degree,
"preference[0]": widget.industry};
String authToken = sharedPreferences.getString("token");
try {
final response = await http.post(
uri,
body: data,
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + authToken,
},
);
final responseJson = json.decode(response.body);
print(responseJson.toString());
if (response.statusCode == 200 || response.statusCode == 201) {
//upload image to server after success response
uploadImage(_image);
NetworkUtils.showToast("Profile successfully update!");
});
} else{
setState(() {
_isLoading = false;
});
NetworkUtils.showSnackBar(_scaffoldKey, 'An error occurred. Please try again');
}
return responseJson;
} catch (exception) {
print(exception.toString());
setState(() {
_isLoading = false;
});
NetworkUtils.showSnackBar(_scaffoldKey, 'An error occurred. Please try again');
}
}
uploadImage(File image) async{
var request = http.MultipartRequest(
"POST",
Uri.parse(NetworkUtils.host +
AuthUtils.endPointUpdateProfile));
request.files.add(await http.MultipartFile.fromPath(
'image',
image.path,
));
try {
var streamedResponse = await request.send();
var response = http.Response.fromStream(streamedResponse);
return response;
} catch (e) {
rethrow;
}
}
}
if(_image!=null){
设置状态(){
_isLoading=true;
});
SharedReferences SharedReferences=等待SharedReferences.getInstance();
var uri=NetworkUtils.host+
AuthUtils.updateSessionRequest;
地图数据={U方法”:“补丁”,
“first_name”:widget.first_name,
“姓氏”:widget.last\u name,
“phone”:widget.phone,
“工业”:小部件工业,
“国家”:widget.country,
“状态”:widget.state,
“fav_quote”:widget.fav_quote,
“bio_兴趣”:widget.bio_文本,
“条款”:“1”,
“公司”:widget.company,
“位置”:widget.job\u位置,
“linked_in”:widget.linkedin_配置文件,
“机构”:widget.institution,
“学位”:小工具。学位,
“首选项[0]”:widget.industry};
String authToken=SharedReferences.getString(“令牌”);
试一试{
最终响应=等待http.post(
乌里,
正文:数据,
标题:{
“接受”:“应用程序/json”,
“授权”:“持有人”+authToken,
},
);
final responseJson=json.decode(response.body);
打印(responseJson.toString());
如果(response.statusCode==200 | | response.statusCode==201){
//成功响应后将图像上载到服务器
上传图像(_图像);
NetworkUtils.showtoos(“配置文件成功更新!”);
});
}否则{
设置状态(){
_isLoading=false;
});
NetworkUtils.showSnackBar(_scaffoldKey,'发生错误。请重试');
}
返回响应;
}捕获(例外){
打印(exception.toString());
设置状态(){
_isLoading=false;
});
NetworkUtils.showSnackBar(_scaffoldKey,'发生错误。请重试');
}
}
上载映像(文件映像)异步{
var request=http.MultipartRequest(
“职位”,
parse(NetworkUtils.host+
AuthUtils.endPointUpdateProfile));
request.files.add(等待http.MultipartFile.fromPath(
“图像”,
image.path,
));
试一试{
var streamdresponse=等待请求。发送();
var response=http.response.fromStream(streamdresponse);
返回响应;
}捕获(e){
改头换面;
}
}
}
您需要像这样传递图像
request.files.add(await http.MultipartFile.fromPath(
'image',
_image,
));
下面是一个如何使用http传递文件和字符串的示例
var request = http.MultipartRequest(
"POST",
Uri.parse("http://....."));
request.fields['first_name'] = widget.first_name;
request.fields['last_name'] = widget.last_name;
.....
request.files.add(await http.MultipartFile.fromPath(
'image',
path,
));
try {
var streamedResponse = await request.send();
var response = http.Response.fromStream(streamedResponse);
return response;
} catch (e) {
rethrow;
}
仅从上面开始,稍加修改
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void executePostMethod(String title) async {
var request = http.MultipartRequest("POST", Uri.parse("https://localhost:44377/API/GetStateList"));
request.fields['CountryID'] = "1";
// .....
//request.files.add(await http.MultipartFile.fromPath('image',path,)
//);
// send request to upload image
await request.send().then((response) async {
//print(response);
response.stream.transform(utf8.decoder).listen((value) async {
print(value);
// print("ResponseVal: $value");
if (response.statusCode == 200) {
var imgUploadData = json.decode(value);
print(imgUploadData);
} else {
throw Exception("Faild to Load!");
}
});
}).catchError((e) {
print(e);
});
}
尝试打印值
uri
uri是否正确。错误来自数据中的_imageam设置。请再次检查问题中的我的错误消息。您的图像是列表
?否。这是一个单一的图像用户档案感谢这一点。我是否要从表单数据体中删除“image”属性?image是您要传递给服务器的参数的名称。请向我们显示您的最新代码和最新错误。您是否尝试使用其他测试api工具测试api是否正常工作?是。它起作用了。因为除了图像之外,我的formData中的其他值都会发布到服务器。