Home > other >  How to send more than 1 image to the APi using multiport in flutter
How to send more than 1 image to the APi using multiport in flutter

Time:02-21

List<File>? myFile=[];

this is my list containing image files, on button pressed i am passing my data using following method but my images are not going on back end. Kindly help me to solve this problem.Thanks in advance.

List<ByteStream> stream =[];
List length=[];
List<MultipartFile> multiPort=[];

for(int i=0; i<myFile!.length;i  )
{
  stream.add(new http.ByteStream(myFile![i].openRead()));
  stream[i].cast();
  length.add(await myFile![i].length());
  multiPort.add(new http.MultipartFile('myFile$i', stream[i], length[i]));
}

Map<String, String> data = {
  "celebrity_id": id.toString(),
  "name": userNameController.text,
  "email": emailController.text,
  "phone": phoneController.text,
  "subject": subjectController.text,
  "description": detailsController.text,
};


Map<String, String> auth = {"Authorization": "Bearer ${token.toString()}"};


final multiPartRequest = new http.MultipartRequest('POST', url)
    ..fields.addAll(data)
    ..headers.addAll(auth)
    ..files.addAll(multiPort);

If I print my above lists on console then I am getting this [Instance of 'ByteStream', Instance of 'ByteStream', Instance of 'ByteStream'] [2931645, 77174, 456585] [Instance of 'MultipartFile', Instance of 'MultipartFile', Instance of 'MultipartFile']

CodePudding user response:

Future uploadmultipleimage(List images) async {
  var uri = Uri.parse("");
  http.MultipartRequest request = new http.MultipartRequest('POST', uri);
  request.headers[''] = '';
  request.fields['user_id'] = '10';
  request.fields['post_details'] = 'dfsfdsfsd';
  //multipartFile = new http.MultipartFile("imagefile", stream, length, filename: basename(imageFile.path));
  List<MultipartFile> newList = new List<MultipartFile>();
  for (int i = 0; i < images.length; i  ) {
    File imageFile = File(images[i].toString());
    var stream =
        new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
    var length = await imageFile.length();
    var multipartFile = new http.MultipartFile("imagefile", stream, length,
        filename: basename(imageFile.path));
    newList.add(multipartFile);
  }
  request.files.addAll(newList);
  var response = await request.send();
  if (response.statusCode == 200) {
    print("Image Uploaded");
  } else {
    print("Upload Failed");
  }
  response.stream.transform(utf8.decoder).listen((value) {
    print(value);
  });
}

CodePudding user response:

I suggest use dio It is powerful Http client for Dart.

List<XFile>? _imageFileList;
uploadFile()async{  List<MultipartFile> multipartImageList = <MultipartFile>[];
 
    for (XFile image in _imageFileList!) {
     
      MultipartFile multifile=await   MultipartFile.fromFile(image.path);
    

      multipartImageList.add(multipartFile);
      print(multipartImageList[0].length);
    
  } 

  FormData formData = FormData.fromMap({
"celebrity_id": id.toString(),
"name": userNameController.text,
"email": emailController.text,
"phone": phoneController.text,
"subject": subjectController.text,
"description": detailsController.text,
"imagefile":multipartImageList
  });
}
 Dio dio = Dio();

  final response = await dio.post(
    url, //your url here
    data: formData ,
    options: Options(
        contentType: 'multipart/form-data',
        headers: {"Authorization": "Bearer $yourToken"},
        followRedirects: false,
        validateStatus: (status) {
          return status! <= 500;
        }),
  );
  print(response.statusCode);
  print(response.data);
  • Related