【问题标题】:Flutter Sending Data to API (Image and Form)Flutter 向 API 发送数据(图像和表单)
【发布时间】:2021-10-01 01:53:29
【问题描述】:

我可以将图像发送到 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;
}

【问题讨论】:

    标签: flutter flutter-layout flutter-dependencies flutter-web flutter-animation


    【解决方案1】:

    使用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!');
    

    该示例取自documentation,并根据您的问题进行了调整。

    【讨论】:

      【解决方案2】:

      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);
      

      【讨论】:

      • 你能解释一下你为什么使用这个'./text.txt' '/info'
      • ./text.txt 是一个示例,您应该处理您的文件,/info 是您的 API URL 地址
      • 在http vs Dio上有一个Reddit帖子here我认为在添加额外依赖之前值得考虑一下,
      • 是的,您是对的,但是每个类似的软件包都有其自身的优点和缺点,您应该根据您的项目要求在它们之间做出正确的选择。我更喜欢使用 Dio 进行上传/下载(formData)并使用 HTTP 进行普通(JSON)请求。
      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 2021-01-19
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多