简体   繁体   中英

Image Upload in Flutter Using Http post method

I'm new in this Framework and I want to Upload the Image along with the User name id and wmail and phone, but Unable to to that I'm getting error

this is the Image get image function

  File _image;
  final picker = ImagePicker();

  Future getImage() async {
    pickedFile = await picker.getImage(source: ImageSource.gallery);

    setState(() {
      if (pickedFile != null) {
        _image = File(pickedFile.path);
      } else {
        print('No image selected.');
      }
    });
  }

Here i have written the Code for Upkoadung How to do Please help me with that

Future updateUserApiCall(
      String name, String email, String mobile, File profile) async {
    
    String token;
    var userId;
    SharedPreferences storage = await SharedPreferences.getInstance();
    token = storage.getString("apiToken");
    userId = storage.getInt("id");


    String url = "https://www.example.com/api/updateprofile";

    final response = await http.post(
      url + "?page=" + "",
      body: json.encode({
        'user_id': userId,
        'email': email,
        'name': name,
        'phone': mobile,
        'image': profile,
      }),
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": "Bearer " + token,
      },
    );

    if (response.statusCode == 200) {
      print(response.body);
      return UpdateProfileResponseModel.fromJson(
        json.decode(response.body),
      );
    } else if (response.statusCode == 400) {
      print(response.body);
      return ErrorResponseModel.fromJson(
        json.decode(response.body),
      );
    } else if (response.statusCode == 422) {
      print(response.body);
      return ValidationErrorResponseModel.fromJson(
        json.decode(response.body),
      );
    } else {
      print(response);
      throw Exception('Failed to load data!');
    }
  }
}

As far as I know you can not pass image data using just http.post method. You have to use Multipart Request. I have also faced similar problem and asked a similar question in StackOverFlow. Please check the link below: uploading image using file_picker flutter to a nodejs server

My use case was updating image of an user, I have used the following code to send image to a node server.

Future<bool> updateImage(File imageFile, AuthModel authModel) async{
  final String _accessToken = 'abc';
  final String url =
      'https://justyourserverURL.com/update';

  print("auth : " + _accessToken);
  var request = http.MultipartRequest('POST', Uri.parse(url));

  request.headers['Authorization'] = _accessToken;
  // request.fields['id'] = '104';
  // request.fields['firstName'] = authModel.data.firstName;
  // request.fields['lastName'] = authModel.data.lastName;
  // request.fields['surname'] = authModel.data.surname;

  request.files.add(await http.MultipartFile.fromPath('file', imageFile.path));
  var res = await request.send();
  final respStr = await res.stream.bytesToString();
  print('responseBody: ' + respStr);
  if(res.statusCode==200){
    setCurrentUser(respStr);
    currentUser = authModelFromJson(respStr);
    return true;
  } else {
    print(respStr);
    print('Failed');
    return false;
  }
}

To pass username or id just pass data using request.fields['user_id'] = userId.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM