Home > Enterprise >  I am trying to make a call to an API with https.MultipartRequest in Flutter
I am trying to make a call to an API with https.MultipartRequest in Flutter

Time:04-01

I am trying to consume this API for dart using Flutter: https://pixcut.wondershare.com/api.html. My images are saved in the database as strings, and I am using methods to convert to string, Uint8list or Image as you can see below. I am trying to use http.MultipartRequest to get the image without background, but I get this error:

[log] {"Code":10001,"Msg":"fail msg : http: no such file","Data":null}


void removeBackground(String image) async {
    var request = http.MultipartRequest(
        "POST", Uri.parse('https://pixcut.wondershare.com/openapi/api/v1/matting/removebg'));
    request.headers.addAll(
      {
        r'Content-Type': 'multipart/form-data',
        r'appkey': '061c4600615d101a56330357cafce7d9',
      },
    );
    request.files
        .add(http.MultipartFile.fromBytes('content', CleverCloset.dataFromBase64String(image) // use the real name if available, or omit
       ));

    await request.send().then((response) {
      http.Response.fromStream(response).then((onValue) {
        try {
          log(onValue.body);
          //stackChildren.add(MoveableStackItem(CleverCloset.imageFromBase64String(onValue.body).image));
          log("bb");
          setState(() {

          });
          // get your response here...
        } catch (e) {
          log(e.toString());
          log("ddd");
          // handle exeption
        }
      });
    });
  }

static Uint8List dataFromBase64String(String base64String) {
    return base64Decode(base64String);
  }

  static String base64String(Uint8List data) {
    return base64Encode(data);
  }

CodePudding user response:

import package dio https://pub.dev/packages/dio

And replace those codes with your own code

 Future<String> uploadImage(File file) async {
    var dio = Dio();
    var url = "https://pixcut.wondershare.com/openapi/api/v1/matting/removebg";
     String fileName = file.path.split('/').last;
    FormData formData = FormData.fromMap({
      "content": await MultipartFile.fromFile(file.path, filename:fileName),
    });
    var response = await dio.post(url, data: formData,
        options: Options(contentType: "multipart/form-data",
            headers: {"appkey":"061c4600615d101a56330357cafce7d9"}));
    print(response.statusCode);
    return response.data;
  }

CodePudding user response:

The problem was that I should pass a file.path, so I saved the image in a temporary file, to pass the path, get the bytes and send the bytes with the code below, now it's working as a charm!

Future<void> removeBackground(context, setState, Uint8List image) async {
    ProgressDialog pd = ProgressDialog(context: context);
    pd.show(max: 100, msg: 'Removing background...',
        backgroundColor: const Color(0xff393432),
    progressValueColor: const Color(0xff393432),
    progressBgColor: const Color(0xffE4BCB4),
    msgColor: const Color(0xffE4BCB4),);
    final appDir = await getTemporaryDirectory();
    File file = File('${appDir.path}/sth.jpg');
    await file.writeAsBytes(image);
    var headers = {
      'x-api-key': '72fe87f131787750e933dcdf80c775fdcf0ad704'
    };
    var request = http.MultipartRequest('POST', Uri.parse('https://sdk.photoroom.com/v1/segment'));
    request.files.add(await http.MultipartFile.fromPath('image_file', file.path));
    request.headers.addAll(headers);
    var response = await request.send();
    if (response.statusCode == 200) {
      final List<int> _bytes = [];
      response.stream.listen((value) {
        _bytes.addAll(value);
      }).onDone(() async {
        await file.writeAsBytes(_bytes);
        pd.close();
        setState(() {
          var a = CleverCloset.base64String(file.readAsBytesSync());
          stackChildren.add(MoveableStackItem(CleverCloset.imageFromBase64String(a).image));
        });
      });

    }
    else {
      setState(() {
        var base64String = CleverCloset.base64String(image);
        stackChildren.add(MoveableStackItem(CleverCloset.imageFromBase64String(base64String).image));
      });
    }
  }
  • Related