Search code examples
flutterrestdarthttp

How to upload Multiple Images to rest API in Flutter?


I am trying to upload upload multiple images to Rest API in flutter. the code i have written is given below:

  final List<File> _image = [];
  Future<Future<bool?>?> uploadImage(filePath, url) async {

  if (_image.length > 0) {
  for (var i = 0; i < _image.length; i++) {
    print(_image.length);
    var request =
        http.MultipartRequest('POST', Uri.parse(url + _scanQrCode));
    print(Uri.parse(url + _scanQrCode));
    request.files.add(http.MultipartFile.fromBytes(
      'picture',
      File(_image[i].path).readAsBytesSync(),
      filename: _image[i].path.split("/").last
    ));
    var res = await request.send();
      var responseData = await res.stream.toBytes();
      var result = String.fromCharCodes(responseData);
      print(_image[i].path);
  }

  _submitedSuccessfully(context);
}else{
  return Fluttertoast.showToast(
      msg: "Please Select atleast one image",
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
      timeInSecForIosWeb: 1,
      backgroundColor: Colors.red,
      textColor: Colors.white,
      fontSize: 16.0
  );
}
}

The code is not working, the image is not getting uploaded. Please anyone help me to solve this problem


Solution

  • change your code to :

    final List<File> _image = [];
    Future<Future<bool?>?> uploadImage(String url) async {
         // create multipart request
         var request = http.MultipartRequest('POST', Uri.parse(url + _scanQrCode));
         
         
          if (_image.length > 0) {
            for (var i = 0; i < _image.length; i++) {
              request.files.add(http.MultipartFile('picture',
              File(_image[i].path).readAsBytes().asStream(), File(_image[i].path).lengthSync(),
              filename: basename(_image[i].path.split("/").last)));
            }
            
            // send
            var response = await request.send();
    
          
            // listen for response
            response.stream.transform(utf8.decoder).listen((value) {
              debugPrint(value);
             _submitedSuccessfully(context);
           });
        }
        else{
      return Fluttertoast.showToast(
          msg: "Please Select atleast one image",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0
         );
       }
    }