Sudhansu Joshi
Sudhansu Joshi

Reputation: 265

image uploading failing using dio package

I am trying to upload an image in flutter using Dio package but its failing. I need to send an image in formdata.

API >> needs request body as imageUpload:image

Code for image upload

 static Future uploadProfilePicToS3(File imageFile) async {
    try {
      FormData formData = new FormData.from(
          {'imageUpload': new UploadFileInfo(imageFile, "profile_pic.jpg")});
      var response =
          await Dio().post(UPLOAD_PROFILE_PIC, data: {'imageUpload': formData});
      print(response.statusCode);
    } catch (error) {
      throw (error);
    }
  }

Error >>>

E/flutter ( 4025): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: DioError [DioErrorType.DEFAULT]: Converting object to an encodable object failed: Instance of 'UploadFileInfo'#0

Let me know if there is any other way.

Upvotes: 2

Views: 3239

Answers (2)

Rahman Rezaee
Rahman Rezaee

Reputation: 2165

use this code

Future<ImageProperty> uploadImage(File imageFile, processfunction) async {
    final StringBuffer url = new StringBuffer(BASE_URL + "/wp-json/wp/v2/media");
 
     Dio dio = new Dio();
     var token = await _getToken();
     try {
        FormData formData = FormData.fromMap(
          {"file": await MultipartFile.fromFile(imageFile.path)},
        );
        print(url);
       if (token != null) {
          dio.options.headers["Authorization"] = "Bearer $token";

          print(dio.options.headers);
        }
      var response = await dio.post(
         url.toString(),
         data: formData,
         onSendProgress: processfunction,
     );

     print(response.data);
      return Future.value(response.data);
   } on DioError catch (e) {
     print(e);
 }

}

Upvotes: 0

MahdiGharooni
MahdiGharooni

Reputation: 11

I used dio for post a file path with some other information in this way :

  Dio dio = new Dio();
  FormData formData = new FormData();
  formData.add(
    "apiKey",
    "my_api_key",
  );
  formData.add(
    "file",
    "image_path",
  );
  Response response = await dio.post(
    "https://localhost",
    data: formData,
    onSendProgress: (int sent, int total) {
      // do something
    },
  ).catchError((onError) {
    throw Exception('something');
  });

Upvotes: 1

Related Questions