Flutter将数据发送到API(图像和表单)



我能够发送图像到API,但在表单数据的情况下,它不上传到API你能帮我吗?

final String uploadUrl = 
 'https://demo.likemyfiles.com/DS/api/api_supervisor/upload_attend_selfie';
var res = await uploadImage(_imageFile.path, uploadUrl);

图片是通过API上传的,但是表单不是

Future<String> uploadImage(filepath, url) async {
   // No issue in the keyWords
  Map mapeddate ={
  'date':"23-07-2021",
  'time':"05:37",
  'lat':"28.535517",
  'lng':"77.391029",
  'location':"Noida Sector 51 Gautam Buddh Nagar India, 201303",
  'activity_id':"4",
  'supervisor_id':"3",
};
var request = http.MultipartRequest('POST', Uri.parse(url));
request.files.add(await http.MultipartFile.fromPath('userfile', filepath));
var res = await request.send();
return res.reasonPhrase;
}

使用MultipartRequest,您可以将表单数据添加为fields

var uri = Uri.parse('https://example.com/create');
Map mapeddate ={
  'date':"23-07-2021",
  'time':"05:37",
  'lat':"28.535517",
  'lng':"77.391029",
  'location':"Noida Sector 51 Gautam Buddh Nagar India, 201303",
  'activity_id':"4",
  'supervisor_id':"3",
};
var request = http.MultipartRequest('POST', uri)
  ..fields = mapedDate
  ..files.add(await http.MultipartFile.fromPath(
      'userfile', filepath,
      contentType: MediaType('image', 'jpeg')));
var response = await request.send();
if (response.statusCode == 200) print('Uploaded!');

该示例取自文档并根据您的问题进行了修改。

HTTP包不能发送表单数据,你应该使用Dio包

var formData = FormData.fromMap({
  'name': 'wendux',
  'age': 25,
  'file': await MultipartFile.fromFile('./text.txt', filename: 'upload.txt'),
 
});
var response = await dio.post('/info', data: formData);

相关内容

  • 没有找到相关文章

最新更新