亲爱的,我是flutter的新手,我想将来自flutter的发帖请求发送到服务器 这是邮递员的请求
帖子标题:
键值
接受:application / json
Content-Type:应用程序/ x-www-form-urlencoded
后验证:
熊代币
帖子正文:
键:值
地址:地址
说明:说明
反馈:反馈
media:download.png
我想从颤抖中提出这个要求 这是我的代码:
File _img; // taken by camera
Map<String,String> headers = {
'Content-Type':'application/json',
'Authorization': 'Bearer $token',
};
final msg = jsonEncode({
"address" : _address,
"description": _description,
"feedback" : _techicalSupport,
"media" : _img;
});
try{
var response = await http.post(
"url",
headers: headers,
body: msg,
);
print("${response.toString()}");
}catch(e){
print("${e.toString()}");
}
我收到此错误: 未处理的异常:将对象转换为可编码对象失败:'_File'的实例
注意:不是必需的媒体,当我从主体中删除它时,它会在数据库中创建记录
我想在体内添加媒体。 我该怎么办...
答案 0 :(得分:1)
这是我的问题的答案,我使用了 Dio 库:
extractFeatures
答案 1 :(得分:0)
您应使用MultipartRequest发送文件。
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
void send() async {
final msg = {
"address": "test",
"description": "test",
"feedback": "test",
};
File _img;
var image = await ImagePicker.pickImage(source: ImageSource.camera);
_img = image;
var response = await http.MultipartRequest(
'POST', Uri.parse("url"))
..fields.addAll(msg)
..files.add(http.MultipartFile.fromBytes('image', _img.readAsBytesSync(),
contentType: MediaType('image', 'jpeg'), filename: 'test.jpg'));
print(response);
}
答案 2 :(得分:0)
您需要将_img
转换为MultipartFile
MultipartFile file=MultipartFile.fromBytes(
'media', await filePath.readAsBytes(),
filename: 'FILE_NAME');
var request = http.MultipartRequest("POST", Uri.parse(url));
if (files != null) request.files.add(file);
答案 3 :(得分:0)
1。配置FilePicker库(可选步骤,您可以使用任何库选择文件)
然后选择文件
File file = await FilePicker.getFile();
import 'package:dio/dio.dart';
然后
FormData formData = FormData.fromMap({
"FIELD_NAME_WEBSERVICE_HERE": await MultipartFile.fromFile(imageFile.path,filename: "anyname_or_filename"),
"FIELD_NAME_WEBSERVICE_HERE":"sample value for another field"),
});
var response = await Dio().post("FULL_URL_HERE", data: formData);
print(response);