1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] Dio FormData in Flutter: Error Sending Multipart File to API causing error type...

Discussão em 'Mobile' iniciado por Stack, Outubro 3, 2024 às 21:33.

  1. Stack

    Stack Membro Participativo

    type 'String' is not a subtype of type 'Map<String, dynamic>' in type cast


    I’m working on a Flutter app where users can update their profiles, including uploading a profile picture and a cover photo. I'm using Dio for handling HTTP requests and multipart file uploads.

    I have trouble uploading the image files (e.g., profile_picture and cover_photo) to the backend. The request keeps failing with errors related to the way the FormData is formatted. I suspect that Dio isn’t interpreting the FormData correctly.

    Below is a simplified version of my code.

    Future<void> updateUserProfile({
    File? coverPhoto,
    File? profilePhoto,
    }) async {
    try {
    // Prepare the form data with fields
    FormData formData = FormData.fromMap({
    "first_name": "Tupac",
    "last_name": "shakur",
    "email": "thuglife@gmail.com",
    });

    // Add cover photo if it exists
    if (coverPhoto != null) {
    final result = _preparePhotoFile(coverPhoto, "cover photo");
    if (result is String) {
    print(result);
    return; // Stop if there's an error
    }

    final [type, subtype] = result as List<String>;
    formData.files.add(
    MapEntry(
    "cover_photo",
    await MultipartFile.fromFile(
    coverPhoto.path,
    filename: path.basename(coverPhoto.path),
    contentType: MediaType(type, subtype),
    ),
    ),
    );
    }

    // Add profile photo if it exists
    if (profilePhoto != null) {
    final result = _preparePhotoFile(profilePhoto, "profile picture");
    if (result is String) {
    print(result);
    return; // Stop if there's an error
    }

    final [type, subtype] = result as List<String>;
    formData.files.add(
    MapEntry(
    "profile_picture",
    await MultipartFile.fromFile(
    profilePhoto.path,
    filename: path.basename(profilePhoto.path),
    contentType: MediaType(type, subtype),
    ),
    ),
    );
    }

    // Sending the request
    Dio dio = Dio();
    final response = await dio.post(
    "https://example.com/update-profile",
    data: formData,
    options: Options(contentType: "multipart/form-data"),
    );

    print(response.data);
    } catch (e) {
    print('Error: $e');
    }
    }


    /// Prepares the photo file by validating its MIME type and ensuring it's in an accepted format.
    dynamic _preparePhotoFile(File photo, String fieldName) {
    // Determine MIME type of the file
    final mimeType = lookupMimeType(photo.path);

    // Validate MIME type is supported
    if (mimeType == null) {
    return 'Unsupported image format for $fieldName';
    }

    // Check if MIME type is among the supported image formats
    if (!['image/jpeg', 'image/png', 'image/bmp', 'image/webp'].contains(mimeType)) {
    return 'Unsupported image format for $fieldName';
    }

    // Return MIME type split into type and subtype (e.g., "image/jpeg" -> "image", "jpeg")
    return mimeType.split('/');
    }


    Steps I’ve Taken to Troubleshoot:

    1. Checked the File Path and Validation Ensured that the file exists and can be accessed. Logged the file path and confirmed it's correct.
    2. Tested With and Without Files
    3. Checked the backend logs but the request is never sent because of the error

    Continue reading...

Compartilhe esta Página