Upload image to the server with the form data in flutter

418

I had a similar problem a while ago, and i used the Dio dependency instead of the classical Http link.

The code is very similar, and i can gave you an example.

final File file = File("${documentDirectory.path}/picture.png");

  final httpDio = dio.Dio();
  final formData = dio.FormData.fromMap({
    "data": "{}",
    "files.image": await dio.MultipartFile.fromFile(
        "${documentDirectory.path}/picture.png",
        filename: "picture.png",
        contentType: MediaType('image', 'png'))
  });

  try {
    final dio.Response response = await httpDio.post(
        "ApiEndpoint/avatars",
        data: formData,
        options: dio.Options(headers: {"Authorization": "Bearer yourTokenIfNeeded"}));
    if (response.statusCode == 200) {
      // Success
    }
  } on dio.DioError catch (e) {
    if (e.response != null) {
      // Error
      print(e.response.data);
      return;
    }
  }

Don't forgot to update the API endpoint and route as well as your auth authorization if you need one.

Share:
418
Masoud H
Author by

Masoud H

Updated on December 26, 2022

Comments

  • Masoud H
    Masoud H over 1 year

    i using the ImagePicker package in the dart when i pick the image i want to upload this to the server with the form data but when i try to send this i give this error

    " Unhandled Exception: FileSystemException: Cannot retrieve length of file, path = 'File: '/storage/emulated/0/Android/data/com.example.aloteb/files/Pictures/scaled_image_picker3594752094355545880.jpg'' " and this is my code for sending to the server

    var request = http.MultipartRequest('POST', Uri.parse(url));
    request.fields.addAll({
      'data': '$map'
    });
    request.files.add(await http.MultipartFile.fromPath('image',picproviderformdate.getPAth.toString()));
    request.headers.addAll(headers);
    http.StreamedResponse response = await request.send();
    if (response.statusCode == 200) {
      print(await response.stream.bytesToString());
    }
    
    else {
      print(response.reasonPhrase);
    }
    

    and this is my ImagePickercode

    picprovider pic = Provider.of<picprovider>(context,listen: false);
        File image = await ImagePicker.pickImage(
            source: ImageSource.gallery, imageQuality: 50);
    
        setState(() {
          _image = image;
        });
        print(_image);
        pic.setpathe(_image);
    

    can any one help me for solve this problem?