i am trying to upload multiple images using dio mathod and multipart but its giving error

Viewed 40

when i print _images list it shows that 'instance of multipart' and when i send list of imageFileList this doesn't accept by server.

also what is the use of multipart in sending images? here is the response error from server response from server error 500

import 'dart:io';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

var token;

Dio dio = Dio();
List<dynamic>? _images = [];
var apiURL = 'https://denga.r3therapeutic.com/public/api/addpost';
FormData formData = FormData();
Future<String> adminAddproperty({
  title,
  address,
  price,
  area,
  bedrooms,
  bathrooms,
  parking,
  other,
  description,
  List<File>? imageFileList,
  context,
}) async {
  for (int i = 0; i < imageFileList!.length; i++) {
    var image = imageFileList[i].path;

    _images!.add(
        await MultipartFile.fromFile(image, filename: image.split('/').last));
  }

  FormData formData = FormData.fromMap({
    'title': title,
    'address': address,
    'price': price,
    'area': area,
    'bedrooms': bedrooms,
    'bathrooms': bathrooms,
    'parking': parking,
    'others': other,
    'description': description,
    'images[]': imageFileList,
  });

  SharedPreferences pref = await SharedPreferences.getInstance();
  token = pref.getString('token');
  print('AdminApisToken =$token');
  print('_images');

  Response responce;

  responce = await dio.post(apiURL,
      data: formData,
      options: Options(headers: {
        HttpHeaders.authorizationHeader: "Bearer $token",
      }));
  print('Responce: $responce');
  return '';
}
    
1 Answers

I faced a similar situation and I solved it by adding the content type to the MultipartFile, something like this:

await MultipartFile.fromFile(picture.path, contentType: MediaType.parse(image.mimeType)

Or hardcoding the type MediaType('image', 'jpeg'). The MediaType is part of the package:http_parser/http_parser.dart package.

Hope it helps!

Related