Flutter 如何将颤振应用程序中的图像上传到服务器并解码服务器的json响应?
我的服务器上有一个端点,它接受多部分/表单数据并将json作为响应发送回。Flutter 如何将颤振应用程序中的图像上传到服务器并解码服务器的json响应?,flutter,dart,Flutter,Dart,我的服务器上有一个端点,它接受多部分/表单数据并将json作为响应发送回。 我想从我的flatter应用程序向我的服务器发送一个图像,并解码从服务器接收到的json。您可以使用http.MultipartRequest进行解码 例如:- static Future<UploadImageRes> uploadImage(int id, File imageFile) async { if (imageFile != null) { var stream = n
我想从我的flatter应用程序向我的服务器发送一个图像,并解码从服务器接收到的json。您可以使用http.MultipartRequest进行解码 例如:-
static Future<UploadImageRes> uploadImage(int id, File imageFile) async {
if (imageFile != null) {
var stream = new http.ByteStream(imageFile.openRead());
var length = await imageFile.length();
String token = PreferenceUtils.getString(AppConstants.LOGGED_IN);
var uri = Uri.parse(UrlConstants.ADD_RECIPE_PHOTO);
LogUtils.d("====uri : $uri");
LogUtils.d("====recipeId : $id");
var request = new http.MultipartRequest("POST", uri);
String fileName = imageFile.path.split("/").last;
var multipartFile = new http.MultipartFile('photo', stream, length,
filename: fileName, contentType: new MediaType('image', 'jpeg'));
request.headers.addAll({"Authorization": "Bearer $token"});
request.files.add(multipartFile);
request.fields["recipeId"] = "$id";
var response = await request.send();
var statusCode = response.statusCode;
LogUtils.d("====statusCode : $statusCode");
if (statusCode < 200 || statusCode >= 400) {
throw new ApiException("Uploading failed");
}
final respStr = await response.stream.bytesToString();
return Future.value(UploadImageRes.fromJson(JsonDecoder().convert(respStr)));
} else {
throw new ApiException("Uploading failed");
}
}
static Future uploadImage(int-id,File-imageFile)异步{
if(imageFile!=null){
var stream=newhttp.ByteStream(imageFile.openRead());
var length=wait imageFile.length();
String token=PreferenceUtils.getString(AppConstants.LOGGED_);
var uri=uri.parse(urlstants.ADD\u RECIPE\u PHOTO);
LogUtils.d(“==uri:$uri”);
LogUtils.d(“==recipeId:$id”);
var request=newhttp.MultipartRequest(“POST”,uri);
字符串文件名=imageFile.path.split(“/”).last;
var multipartFile=new http.multipartFile('photo',stream,length,
文件名:文件名,内容类型:新媒体类型('image','jpeg');
addAll({“Authorization”:“Bearer$token”});
request.files.add(多部分文件);
请求.字段[“recipeId”]=“$id”;
var response=wait request.send();
var statusCode=response.statusCode;
LogUtils.d(“==statusCode:$statusCode”);
如果(状态代码<200 | |状态代码>=400){
抛出新ApiException(“上传失败”);
}
final respStr=wait response.stream.bytesToString();
返回Future.value(UploadImageRes.fromJson(JsonDecoder().convert(respStr));
}否则{
抛出新ApiException(“上传失败”);
}
}
在final respStr=wait response.stream.bytesToString()中代码>您将获得api响应