在颤动中将文件发送到api
Posted
技术标签:
【中文标题】在颤动中将文件发送到api【英文标题】:sending file to api in flutter 【发布时间】:2020-05-23 07:39:44 【问题描述】:我正在尝试将文件从颤振应用程序发送到 api 此 api 接受如下值
这里profileImage
接受File
这是我在flutter中使用的代码
....................
....................
final File _imgfile = widget.imageFile;
print(_fbName + _fbEmail);
final body =
"name": _fbName,
"gender": gender,
"bday": bday,
"email": _fbEmail,
"phone": _phone,
"profileImage": _imgfile
;
print(body);
RegisterUserService.RegisterUser(jsonEncode(body))
.then((success)
if (success)
print('registration successfull');
//passing data to next screens
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => SetupStepThree()));
else
print('registration error !');
);
..................
这就是上面代码调用的服务
class RegisterUserService
static Future<bool> RegisterUser(body) async
final response =
await http.post('$URLS.BASE_URL/user/register', body:body);
var data = response.body;
// print(body);
print(json.decode(data));
// Map<String, dynamic> res_data = jsonDecode(data);
// log(res_data['loginstatus']);
// if (res_data['loginstatus'] == 'olduser')
// return true;
// else
// return false;
//
return false;
但问题是这给了我以下错误。
**
I/flutter ( 4860): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter ( 4860): The following JsonUnsupportedObjectError was thrown while handling a gesture:
I/flutter ( 4860): Converting object to an encodable object failed: Instance of '_File'
**
我想知道这段代码有什么问题以及如何将图像传递给这个端点
【问题讨论】:
使用 Dio() 智能实现多部分文件。 pub.dev/packages/dio 【参考方案1】:为了在 Flutter 中上传文件,你可以使用 MultipartRequest
Uri uri = Uri.parse("$URLS.BASE_URL/user/register");
var fileStream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var request = new http.MultipartRequest("POST", uri);
//add your fields here
request.fields.add("gender","male");
request.fields.add("name","sssss");
var multipartFile = new http.MultipartFile('file', fileStream, length,
filename: <Your file name>);
request.files.add(multipartFile);
var response = await request.send();
//do whatever you want with the response
如果这能解决您的问题,请告诉我
【讨论】:
它给了你什么?以上是关于在颤动中将文件发送到api的主要内容,如果未能解决你的问题,请参考以下文章
在颤动中使用 REST api 将列表数据发送到云 Firestore 时出错
如何在颤动中将 List<Asset> 转换为 List<File>
如何在颤动中将列表数据从一个屏幕传递到另一个屏幕(StatefulWidget)