【问题标题】:Post form data to server flutter将表单数据发布到服务器颤振
【发布时间】:2020-06-14 09:14:46
【问题描述】:

我在向服务器发送post 请求时遇到了很多麻烦。它需要 form data 类型。

这是我输入后得到的错误。

  `image: [The image must be an image.]}}

我的大部分数据都是字符串,除了 intfile Image 由用户从图库中选择。

这是我的代码:

飞镖代码

if(_image!=null){
      setState(() {
        _isLoading = true;
      });
        SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
        var uri = NetworkUtils.host +
            AuthUtils.updateSessionRequest;
        Map<String, String> data = {"_method": "PATCH",
          "first_name": widget.first_name,
          "last_name": widget.last_name,
          "phone": widget.phone,
        "industry":widget.industry,
        "country": widget.country,
        "state": widget.state,
        "fav_quote": widget.fav_quote,
        "bio_interest": widget.bio_text,
        "terms": "1",
        "company": widget.company,
        "position": widget.job_position,
        "linked_in":widget.linkedin_profile,
        "institution": widget.institution,
        "degree": widget.degree,
        "preference[0]": widget.industry};
        String authToken = sharedPreferences.getString("token");
        try {
          final response = await http.post(
            uri,
            body: data,
            headers: {
              'Accept': 'application/json',
              'Authorization': 'Bearer ' + authToken,
            },
          );

          final responseJson = json.decode(response.body);
          print(responseJson.toString());
          if (response.statusCode == 200 || response.statusCode == 201) { 
       //upload image to server after success response
       uploadImage(_image);
              NetworkUtils.showToast("Profile successfully update!");
            });
          } else{
            setState(() {
              _isLoading = false;
            });
            NetworkUtils.showSnackBar(_scaffoldKey, 'An error occurred. Please try again');
          }
          return responseJson;
        } catch (exception) {
          print(exception.toString());
          setState(() {
            _isLoading = false;
          });
          NetworkUtils.showSnackBar(_scaffoldKey, 'An error occurred. Please try again');
        }
    } 

 uploadImage(File image) async{
    var request = http.MultipartRequest(
        "POST",
        Uri.parse(NetworkUtils.host +
            AuthUtils.endPointUpdateProfile));
    request.files.add(await http.MultipartFile.fromPath(
      'image',
      image.path,
    ));

    try {
    var streamedResponse = await request.send();
    var response = http.Response.fromStream(streamedResponse);
    return response;
    } catch (e) {
    rethrow;
    }
  }
  }

【问题讨论】:

  • 尝试打印出值uri
  • uri 是正确的。错误来自数据内的 _image am 设置
  • 请再次检查我在问题中的错误信息
  • 你的头像是List?
  • 不。它是用户个人资料的单个图像

标签: json flutter post form-data


【解决方案1】:

你需要像这样传递你的图像

request.files.add(await http.MultipartFile.fromPath(
        'image',
        _image,
      ));

这里是一个如何使用http传递文件和字符串的例子

 var request = http.MultipartRequest(
              "POST",
              Uri.parse("http://....."));
          request.fields['first_name'] = widget.first_name;
          request.fields['last_name'] = widget.last_name;
                   .....
          request.files.add(await http.MultipartFile.fromPath(
            'image',
            path,
          ));

try {
      var streamedResponse = await request.send();
      var response = http.Response.fromStream(streamedResponse);
      return response;
    } catch (e) {
      rethrow;
   }

【讨论】:

  • 感谢您。那么我要从表单数据主体中删除“图像”属性吗?
  • “图像”是您要传递给服务器的参数的名称。
  • 请告诉我们您的最新代码和最新错误。
  • 您是否尝试过使用其他测试api工具来测试API是否正常工作?
  • 是的。它的工作。因为我的 formData 中的其他值被发布到服务器,除了图像。
【解决方案2】:

仅从上面,稍作修改

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void executePostMethod(String title) async {
  var request = http.MultipartRequest("POST", Uri.parse("https://localhost:44377/API/GetStateList"));
  request.fields['CountryID'] = "1";
  //          .....
  //request.files.add(await http.MultipartFile.fromPath('image',path,)
  //);

   // send request to upload image
    await request.send().then((response) async {
     //print(response);

     response.stream.transform(utf8.decoder).listen((value) async {
        print(value);
        // print("ResponseVal: $value");
        if (response.statusCode == 200) {
          var imgUploadData = json.decode(value);
          print(imgUploadData);          
        } else {
          throw Exception("Faild to Load!");
        }
      });
    }).catchError((e) {
      print(e);
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-23
    • 2020-04-18
    • 1970-01-01
    • 2021-06-03
    • 2020-08-16
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    相关资源
    最近更新 更多