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;
    }
  }
  }
5
  • try print out value uri
    – John Joe
    Mar 2, 2020 at 6:08
  • the uri is correct. the error comes from the _image am setting inside the data
    – Ben Ajax
    Mar 2, 2020 at 6:38
  • please check my error message in the question again
    – Ben Ajax
    Mar 2, 2020 at 6:39
  • your image is List?
    – John Joe
    Mar 2, 2020 at 6:47
  • nope. its a single image for user profile
    – Ben Ajax
    Mar 2, 2020 at 7:04

2 Answers 2

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;
   }
8
  • thanks for this. so am I to remove "image" property from my form data body?
    – Ben Ajax
    Mar 2, 2020 at 7:03
  • The 'image' is the name of the parameter which you want to pass to sever.
    – John Joe
    Mar 2, 2020 at 7:25
  • Please show us your latest code and the latest error.
    – John Joe
    Mar 2, 2020 at 7:47
  • Have you tried using other testing api tool to test whether the API is working?
    – John Joe
    Mar 2, 2020 at 7:55
  • yes. its working. Because other values in my formData get posted to the server except the image.
    – Ben Ajax
    Mar 2, 2020 at 7:59
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);
    });
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.