将表单数据发布到服务器上 [英] Post form data to server flutter

查看:74
本文介绍了将表单数据发布到服务器上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been having a lot of trouble sending a post request to a server. It expects a form data type.

这是我输入后遇到的错误.

This is the error I get after my input.

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

我的大部分数据都是字符串,除了 int file Image (由用户从图库中选择)之外.

Most of my data are strings except for an int and a file Image which is selected from gallery by user.

这是我的代码:

飞镖代码

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

推荐答案

您需要像这样传递图像

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

下面是一个如何使用http传递文件和字符串的示例

Here an example how to pass File and String using 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;
   }

这篇关于将表单数据发布到服务器上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆