1

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.]}}

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

This is my code:

dart code

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;
    }
  }
  }
Ben Ajax
  • 668
  • 2
  • 13
  • 27

2 Answers2

2

You need to pass your image like this

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

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;
   }
John Joe
  • 12,412
  • 16
  • 70
  • 135
1

From the above only, with a little modification

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);
    });
}
Arun Prasad E S
  • 9,489
  • 8
  • 74
  • 87