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

2

1
    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.

Aslant answered 22/4, 2022 at 18:35 Comment(5)
What does print(newList); return?Transcurrent
it returns in the case of uploading two images the following: [Instance of 'MultipartFile', Instance of 'MultipartFile']Aslant
I can't seem to see the problem in this code. Can you print response.statusCode and response.reasonPhrase if that helps?Transcurrent
For every file you are calling it file here: http.MultipartFile("file", You need a different value for each one, if for no other reason than the server can differentiate file 1, 2, 3, etc.Wellington
can u refactor my code to show me how?Aslant
R
5
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);
      });
    }
  }

});

}

Roundhouse answered 13/10, 2022 at 20:38 Comment(1)
This code using bearer token to authenticate the user and I saved it in sharedpreference . Then I got the token and added it to the request headers . This codes are using with aspnet core 6 backendHinshelwood
E
0

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')
    }       
 });
Eichelberger answered 17/8, 2023 at 11:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.