flutter http multipart request to upload a list of images to the server

5.2k Views Asked by At
    Future uploadmultipleimage(List<File>img) async {
  var uri = Uri.parse("http://192.168.15.106/easy/uploadfile.php");
  http.MultipartRequest request = http.MultipartRequest('POST', uri);
  //multipartFile = new http.MultipartFile("imagefile", stream, length, filename: basename(imageFile.path));
  List<MultipartFile> newList = [];
  for (int i = 0; i < img.length; i++) {
    File imageFile = File(img[i].path);
    var stream =
    http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
    var length = await imageFile.length();
    var multipartFile = http.MultipartFile("file", stream, length,
        filename: basename(imageFile.path));
    print(imageFile.path);
    newList.add(multipartFile);
  }
  request.files.addAll(newList);
  print(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);
  });
}

i have this code which i give it a list of images saved in a List variable from file_picker, i want to upload the list items to the server, but when i run this upload function it only upload the last image not the entire list, i want to know how to upload the entire list of images.

2

There are 2 best solutions below

1
يوسف القادري On
Future addProduct() async{
await SharedPreferencesHelper.getPrefString('token', '').then((value) async 
{
    String token;
    if(value != ''){
    token = value;
    var header = {
      "Authorization":"Bearer $token"
    };
    final request = await http.MultipartRequest(
        'POST',
        Uri.parse('${ConstantValues.BASE_URL}products/add-product'),
    );
   request.headers.addAll(header);
    request.fields['Brand'] = brandController.text;
    request.fields['Category'] = selectedCategory!;
    request.fields['SupCategory'] = selectedSupCategory!;
    request.fields['Price'] = priceController.text;
    request.fields['SalePrice'] = salePriceController.text;
    request.fields['IsPupular'] = isPupular.toString();
    request.fields['Description'] = descriptionController.text;
    request.fields['Sizes[]'] = '[]';
    List<http.MultipartFile> files = [];
    for(File file in images){
      var f = await http.MultipartFile.fromPath('Photos',file.path);
      files.add(f);
    }
    request.files.addAll(files);
    var response = await request.send();
    if(response.statusCode == 200) {
      var responseData = await response.stream.toBytes();
      var responseToString = String.fromCharCodes(responseData);
      var jsonBody = jsonDecode(responseToString);
      setState(() {
        print(jsonBody);
      });
    }
  }

});

}

0
mhmd On

You can handle the list of image by index:

Future addProduct(String name, String description, List<File> images) async{
    final request = await http.MultipartRequest(
        'POST',
        Uri.parse('$baseUrl/products/add-product'),
    );

    request.headers.addAll(header);

    request.fields['Name'] = name;
    request.fields['Description'] = description;

    for(int i = 0; i < images.length; i++){
      final f = await http.MultipartFile.fromPath('Photos[$i]',images[i].path);
      request.files.add(f);
    }

    final responseStream = await request.send();
    final response = await http.Response.fromStream(responseStream);

    if(response.statusCode == 200) {
      print("success")
    } else {
      print('failed')
    }       
 });