chandru
chandru

Reputation: 417

Issue with uploading multi part image file with dio in Flutter

I used Dio framework to upload image to server in my flutter app. Dio version 3.0.9. Post method. Added 4 headers Created form data with image and other fields.

I have analysed many more methods. Like degrading Dio to 2.3.1, to use UploadFileInfo method. Not a success. Then with multipartfileupload. Finally this one.

Future<bool> createStoreWithDio() async {
    Map<String, String> headers = {
      "Accept": "application/json",
      "authorization": tokenString,
      "authtype": "admin",
      "Content-Type": "multipart/form-data"
    };
    try {
      FormData formData = new FormData.fromMap({
        "logo": await http.MultipartFile.fromPath("logo", imageFile.path,
            contentType: new MediaType('image', 'png')),
        "name": " Bala ios",
        "description": "_description",
        "website": "www.website.com",
        "password": "Test password",
        "user_name": "Test userInformationName",
        "mobile": "9988776655",
        "email": "[email protected]",
   
      });

      print(formData.fields);
      Response response = await dio
          .post(
        "API",
        data: formData,
        options: Options(
          headers: headers,
        ),
      )
          .then((value) {
        print(value.toString());
      });
      print(response.toString());
    } catch (error) {
      print(error);
    }
  }

imageFile is the file I captured from camera/ gallery.

I am getting 500 exception. Any help would be helpful

Upvotes: 1

Views: 7913

Answers (1)

Abhijith
Abhijith

Reputation: 2327

I am not sure what caused this,this code is used in an app i have change based on your code,but i am not sending any headers so you need to add then try with this code let me know it it's work for you.also make sure you have file imageFile.path also your api url is correct or not make sure you have imported

`'import  package:http_parser/http_parser.dart';
  import 'package:mime/mime.dart';`

 Dio dio = new Dio();
      final mimeTypeData =
      lookupMimeType(imageFile.path, headerBytes: [0xFF, 0xD8]).split('/');
      FormData formData = FormData.fromMap({
        "name": " Bala ios",
        "description": "_description",
        "website": "www.website.com",
        "password": "Test password",
        "user_name": "Test userInformationName",
        "mobile": "9988776655",
        "email": "[email protected]",
        "logo": await MultipartFile.fromFile(imageFile.path,
            contentType: MediaType(mimeTypeData[0], mimeTypeData[1])),
      });

      var response = await dio.post(
        Urls.ImageInsert,
        data: formData,
      );

      var message = response.data['message'];

Upvotes: 2

Related Questions