Maichale
Maichale

Reputation: 29

Upload images list with dio

I've use this code in my application with Dio: 2.2.2 and it works fine, but after upgrading my Dio package version, I must use the MultipartFile option. I tried to use it, but all data sent ok without the images. How can I upgrade this code to use with the latest Dio package version?

Old code:

Future add(name,desc,address,images) async {
    Map ad_data;
    await dio
        .post("${host}/add",
        data: FormData.from({
          "name": "${name}",
          "desc": "${desc}",
          "address": "${address}",
          "image[]": images
              .map((image) =>
              UploadFileInfo(File(image.path), basename(image.path)))
              .toList(),
        }),).then((data) {
      ad_data = data.data;
    });
    return ad_data;
  }

Upvotes: 1

Views: 2068

Answers (3)

mohammad mobasher
mohammad mobasher

Reputation: 777

I have a costum function for uploading one file, you can change it and use.

Dio getBaseDio() {
    var token = "AccessToken";
    Dio dio = Dio(BaseOptions(
        baseUrl: "your base url",
        headers: {
          "Authorization": "Bearer $token",
          "Accept": "application/json",
        }));

    return dio;
}

after this :

Future<Response> postWithFile(
            String url, 
            dynamic body) async {
    return await getBaseDio().post(url, data: body)
    .catchError(
        (error) {
            return error.response;
        },
    );
}

now you can use postWithFile function like this:

FormData formData = FormData.fromMap({
  "param1": "value1",
  "param2": "value2,
  "fileParam": await MultipartFile.fromFile(attachPath, filename: fileName),
});

var result = await postWithFile(url, formData);

I hope I was able to help.

Upvotes: 1

Hamza Siddiqui
Hamza Siddiqui

Reputation: 716

add content type

contentType: MediaType(
      "image", "${item.path.split(".").last}"),

Upvotes: 0

Dhaval Kansara
Dhaval Kansara

Reputation: 3911

Update your add function with the below one... I am using dio: ^4.0.0.

import 'package:path/path.dart';


Future add(name,desc,address,images) async {

var formData = FormData.fromMap({
      'name': name,
      'desc': desc,
      'address': address,
      'files': [
        for (var item in images)
          {
            await MultipartFile.fromFile(item.path,
                filename: basename(item.path))
          }.toList()
      ],
    });


    await dio.post("${host}/add",data:formData).then((data) {
      ad_data = data.data;
    });
    return ad_data;
  }

Upvotes: 2

Related Questions