dio icon indicating copy to clipboard operation
dio copied to clipboard

Multipart: can't upload JSON with image

Open cdprete opened this issue 2 years ago • 0 comments

Hi. I'm trying to execute a POST and a PUT request where I do upload a JSON with, as well, an image file.

Version of the library: 4.0.4 App built for: Windows Flutter doctor output:

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.10.3, on Microsoft Windows [Version 10.0.19044.1586], locale it-CH)
[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[√] Chrome - develop for the web
[√] Visual Studio - develop for Windows (Visual Studio Community 2019 16.11.7)
[!] Android Studio (not installed)
[√] IntelliJ IDEA Community Edition (version 2021.3)
[√] VS Code (version 1.63.2)
[√] Connected device (3 available)
[√] HTTP Host Availability

Code

final String urlSuffix, httpMethod;
      if (id == null) {
        urlSuffix = contactsUrl;
        httpMethod = 'POST';
      } else {
        urlSuffix = singleContactUrl.replaceFirst(':id', id);
        httpMethod = 'PUT';
      }
      final data = FormData.fromMap({
        'data': MultipartFile.fromString(
          await compute(jsonEncode, contact),
          contentType: Headers.jsonMimeType,
        )
      })
      if (contact.image != null) {
        data.files.add(MapEntry(
          'image',
          MultipartFile.fromBytes(contact.image!.toList()),
        ));
      }

      final response = await client.request(
        '$baseUrl/$urlSuffix',
        data: data,
        options: Options(method: httpMethod),
      );

The image payload is simply ignored while, if I pass the JSON as field (instead of file), I get the same as in https://stackoverflow.com/questions/68799973/cannot-send-dio-post-request-with-multiple-form-data-body-json-and-image-with-fl (which is expected given the API).

cdprete avatar Mar 14 '22 22:03 cdprete