3

i try to send image to machine learning model with fast api it works fine with postman but when i try with dio package it gives me error the type is File and i want it to be png or jpg to work with the model and the api

here is the code for selecting image

import 'dart:io';

import 'package:breastcancer1/network/remote/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ImagePickerPage extends StatefulWidget {
  const ImagePickerPage({Key? key}) : super(key: key);

  @override
  _ImagePickerPageState createState() => _ImagePickerPageState();
}

class _ImagePickerPageState extends State<ImagePickerPage> {
  File? imageFile;

  final picker = ImagePicker();

  Future<void> _pickImage() async {
    final pickedFile = await picker.getImage(source: ImageSource.gallery);

    setState(() {
      imageFile = pickedFile != null ? File(pickedFile.path) : null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Image Picker'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (imageFile != null) ...[
              Container(
                  height: 100, width: 100, child: Image.file(imageFile!)),
              const SizedBox(height: 20),
            ],
            ElevatedButton(
              onPressed: _pickImage,
              child: const Text('Select Image'),
            ),
            MaterialButton(
              onPressed: () {
                if (imageFile != null) {
                  print({"is it nulll        ${imageFile}"});
                  DioHelper.postImage(url: 'predict', query: {'image': imageFile}).then((value) {
                    print(value.data['class']);
                    print({"is it nosos nulll${imageFile.runtimeType}"});

                  }).catchError((error) {
                    print(error.toString());
                    print('why');
                  });
                } else {
                  print('No image selected');
                }
              },
              child: Text('press'),
            )
          ],
        ),
      ),
    );
  }
}

and here is the dio code

import 'package:dio/dio.dart';

class DioHelper{
  static Dio? dio;
  static init(){
    dio=Dio(
      BaseOptions(
        baseUrl: 'http://192.168.1.5:8000/',
        receiveDataWhenStatusError: true
      )
    );
  }

  static Future<Response> postImage({
    required String url,
    required Map<String,dynamic> query,
  })
  async
  {
    return await dio!.post( url, queryParameters: query, );
  }
}

and here is the error I/flutter (21041): DioError [bad response]: The request returned an invalid status code of 422.

i tried to ask chat gpt but still nothing it works fine with postman

5
  • 1
    How is the API endpoint expecting the data? Multi-part form data? base64 encoded and passed in the body? because from what I am seeing is that you are trying to post the file as is as a query parameter which from my understanding does not work Commented Apr 13, 2023 at 18:16
  • how spose i send the file to api because the query is the only way i know Commented Apr 13, 2023 at 18:58
  • typically you could use form data and pass the file as a multi-part form data, but you could also base64 encode the file and pass it in a json body. How ever, I would personally go with multi-part form data as it does not increase the payload size by a 1/3rd like base64. Commented Apr 14, 2023 at 19:46
  • If you could also upload a code snippet of the API endpoint that you have using FastAPI it will help clarify how the backend expects to receive the image, which will help others help you Commented Apr 14, 2023 at 19:48
  • it was a problem in how i post the image i forgot about MultipartFile and data parameter in dio Commented Apr 15, 2023 at 10:34

2 Answers 2

2
  static Future<Response> postImage({
    required File file,
    required String url,
    required Map<String, dynamic> query,
  }) async {
    String fileName = file.path.split('/').last;
    var fileExt = fileName.split('.').last;
    var formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(
        file.path,
        filename: fileName,
        contentType: MediaType("image", fileExt),
      ),
    });

    return await dio!.post(url, data: formData, queryParameters: query);
  }

Usually, we are sending files as form data, it supports binary data, allows for the transmission of multiple data types in a single request, uses boundary separation for easy parsing, it's widely supported, and is streaming-friendly.

Plus I'm using http_parser it's dart.dev package with a nice helper to create MediaTypes.

Sign up to request clarification or add additional context in comments.

1 Comment

the mistake was i forgot about MultipartFile and data parameter in dio
1
 MaterialButton(
              onPressed: () async{
                if ( PateintCubit.get(context).imageFile != null) {
                  FormData formData = FormData.fromMap({
                    'image': await MultipartFile.fromFile( PateintCubit.get(context).imageFile!.path),
                  });
                  print({"is it nulll        ${ PateintCubit.get(context).imageFile?.runtimeType}"});
                  DioHelper.postImage(url: 'predict', query: formData).then((value) {
                    print(value.data['class']);
                    print({"is it nosos nulll${ PateintCubit.get(context).imageFile.runtimeType}"});

                  }).catchError((error) {
                    print(error.toString());
                    print('why');
                  });
                } else {
                  print('No image selected');
                }
              },
              child: Text('press'),
            )

what i did to solve it

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.