skip to Main Content

How can I send image to API in string format? This is the code where the data is sent in MultipartFile instance but data['avatar'] accepts string. So how can I do it? Please help me with this.

static Future<Response> updateUserAccount({
    XFile? avatar,
    String? fullName,
    String? email,
    String? oldPhone,
    String? phone,
    String? city,
    String? streetName,
    String? landmark,
    String? oldPassword,
    String? password,
  }) async {
    final dio = Dio();
    String token = await SecureStorageUtils.getToken();
    dio.options.headers['accept'] = '*/*';
    dio.options.headers['content-type'] = 'multipart/form-data';
    dio.options.headers['authorization'] = 'Bearer $token';
    Map<String, dynamic> data = {};
    if (avatar != null) {
      data['avatar'] = await MultipartFile.fromFile(avatar.path);
    }

    if (email != null) {
      data['email'] = email;
    }

    if (oldPhone != null) {
      data['old_phone_number'] = oldPhone;
    }

    if (phone != null) {
      data['phone_number'] = phone;
    }

    if (city != null || streetName != null || landmark != null) {
      final address = {};

      if (city != null) {
        address['city'] = city;
      }

      if (streetName != null) {
        address['street_name'] = streetName;
      }

      if (landmark != null) {
        address['landmark'] = landmark;
      }
      data['address'] = address;
    }

    if (oldPassword != null) {
      data['old_password'] = oldPassword;
    }
    if (password != null) {
      data['password'] = password;
    }
    if (fullName != null) {
      data['full_name'] = fullName;
    }
    print("data: $data");

    FormData formData = FormData.fromMap(data);

    final response = await dio.patch(
      AppUrl.currentUser,
      data: formData,
    );
    return response;
  }

I tried this way using base64Encoding but it did not work.

List<int> fileBytes = await avatar.readAsBytes();
  String base64Avatar = base64Encode(fileBytes);
  data['avatar'] = base64Avatar;

2

Answers


  1. At my case is that i can send json data as the data is string file so i created a class that create base64 e.g.

    class ToImageData {
      static String imagetoData(String? imagepath) {
        final extension = path.extension(
          imagepath!.substring(imagepath.lastIndexOf("/")).replaceAll("/", ""),
        );
        final bytes = File(imagepath).readAsBytesSync();
        String base64 =
            "data:image/${extension.replaceAll(".", "")};base64,${base64Encode(bytes)}";
        return base64;
      }
    }
    

    so whenever i have to send file in json for i call it like this

     // Lets make an example
     final data = {
         "avatar": ToImageData.imagetoData(file.path);
         // result is like this data:image/png;base64,TEWUFDBSJWEH1232347GHSD
        //something long text
     }
    
    final response = await dio.patch(
          AppUrl.currentUser,
          data: data ,
        );
        return response;
    

    I hope this finds you helpful.

    Login or Signup to reply.
  2. For this I have used image_picker and image

    import ‘package:image/image.dart’ as img;

    import ‘package:image_picker/image_picker.dart’;

    File? _image; //Your image-file variable
    
    _image = File(pickedFile.path); //Once user picked image file.
    
    //Upload to API
    
     var fileName;
     if (_image != null) {
        fileName = _image!.path.split('/').last;
      }
     final capturedImage = img.decodeImage(await _image!.readAsBytes())!;
        final orientedImage = img.bakeOrientation(capturedImage);
        final thumbnail = img.copyResize(orientedImage, width: 200);
        await _image!.writeAsBytes(img.encodeJpg(thumbnail)).then((value) async {
         'avatar':
                await MultipartFile.fromFile(_image!.path, filename: fileName)
          _callSaveProfileApi(formData);
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search