djangoflutterdartdioflutter-http

How I upload image with schema to my dio flutter app


I had this endpoint in my django api

I need to upload a image with the post details to create one in my app ,i spend days without any sol in flutter i know how to send to schema without another parameter like image, As a flutter beginner i create the post details in this code:

static Future<Account?> add({required String title,required int price,required String det,required String cate,required int w,required int h,required int bed,required int bath,required int location_id}) async {
Response res = await Dio().post(
    'http://10.0.2.2:8000/api/post/add-post',
    data: jsonEncode(
        {
          "user_id": Account.currentAcc.id,
          "title": title,
          "price": price,
          "details": det,
          "category": cate,
          "bedroom": bed,
          "bathroom": bath,
          "width": w,
          "height": h,
          "location_post_id": location_id
        }
    ),
);

return null;

}


Solution

  • You need to use formdata instead of sending an encoded json (see dio docs at section Sending from data)

    Example for your case:

    var formData = FormData.fromMap({
          "user_id": Account.currentAcc.id,
          "title": title,
          "price": price,
          "details": det,
          "category": cate,
          "bedroom": bed,
          "bathroom": bath,
          "width": w,
          "height": h,
          "location_post_id": location_id,
          'file': await MultipartFile.fromFile('${filePath}',filename: '${fileName}')
    });
    response = await dio.post('http://10.0.2.2:8000/api/post/add-post', data: formData);