Search code examples
flutterdarthttpmultipartform-data

Send multiple file http flutter


I have a list that contains File from camera. And I want to send all of the list to server. How can I reach that?

Future<void> addServiceGrTransaction({List<File>? dataFile}) {
   var url = '$baseUrl/add-service-gr-transaction';
   SharedPreferences prefs = await SharedPreferences.getInstance();
   token = prefs.getString('token');

   var header = {
     'Content-Type': 'application/json',
     'Authorization': '$token'
   };

   Map<String, String> obj = {'data': body.toString()};
   Map<String, String> objFile = {'file': dataFile.toString()};
   var request = http.MultipartRequest('POST', Uri.parse(url))
     ..headers.addAll(header)
     ..fields.addAll(obj)
     ..fields.addAll(objFile);
   for (File file in dataFile!) {
     request.files.add(await http.MultipartFile.fromPath('file', file.path));
   }

   var streamedResponse = await request.send();
   var response = await http.Response.fromStream(streamedResponse);

   if (response.statusCode == 200) {
   } else {
     throw Exception('Error');
   }
}

can I get that with this?


Solution

  • This is how you can update your code for it to work properly as expected.

    • While the philosophy is nice and workable, there are some minor errors that causes the code to not be working properly

    • First, the function Future<void> addServiceGrTransaction({List<File>? dataFile}) { is missing async keyword but it does contain asynchronous tasks

    • The Content-Type should be set to multipart/form-data instead of application/json because you're sending files in the request, not JSON data.

    • The response was correctly obtained, but the code can be simplified by directly awaiting request.send() and using http.Response.fromStream() in a single line.

    • So based on my understanding of what you're trying to achieve, this is how you can update your function or method....

    Future<void> addServiceGrTransaction({List<File>? dataFile}) async {
      var url = '$baseUrl/add-service-gr-transaction';
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String? token = prefs.getString('token');
    
      var headers = {
        'Content-Type': 'multipart/form-data',
        'Authorization': '$token',
      };
    
      var request = http.MultipartRequest('POST', Uri.parse(url));
      request.headers.addAll(headers);
    
      for (File file in dataFile!) {
        var stream = http.ByteStream(file.openRead());
        var length = await file.length();
    
        var multipartFile = http.MultipartFile('file', stream, length,
            filename: file.path.split('/').last);
    
        request.files.add(multipartFile);
      }
    
      var response = await http.Response.fromStream(await request.send());
    
      if (response.statusCode == 200) {
        // When the response status code is `200`, things went well.
      } else {
       // Otherwise, something went wrong! You can try to wrap statements in a try-catch bloc, for better errors handlings
        throw Exception('Error');
      }
    }