Upload multiple files to server side with php from dart

Issue

.dart

  Future<http.Response> uploadFile(String fileName, List<int> fileBytes) async {
try {
  var request = new http.MultipartRequest("POST", Uri.parse("https://****/***/fileupload.php"));

  for (var i = 0; i < uploadedImage.length; i++) {
    selectedFilesBytes = List.from(uploadedImage[i]);
    request.files.add(http.MultipartFile.fromBytes('file', selectedFilesBytes, contentType: MediaType('application', 'octet-stream'), filename: files[i].name));
  }

  print("request.files.length");
  print(request.files.length);
  var streamedResponse = await request.send();

  return await http.Response.fromStream(streamedResponse);
} catch (e) {
  print(e);
}

fileupload.php

    <?php 

 // Count total files
 $countfiles = count($_FILES['file']);
 error_log($countfiles);
 // Looping all files
 for($i=0;$i<$countfiles;$i++){
   $filename = $_FILES['file']['name'][$i];
   
   // Upload file
   move_uploaded_file($_FILES['file']['tmp_name'][$i],'upload/'.$filename);
    
 }

?>

Hi,
I have a problem about file upload from dart to php. When I print out print(request.files.length); it gives me the file count which I choose for upload.
But in php side $countfiles = count($_FILES['file']); always returns 1.
why it could be?

Solution

Thanks for the answer @CBroe. It works. I added the recent codes down.

.dart

  Future<http.Response> uploadFile(String fileName, List<int> fileBytes) async {
try {
  var request = new http.MultipartRequest("POST", Uri.parse("https://****/***/fileupload.php"));

  for (var i = 0; i < uploadedImage.length; i++) {
    selectedFilesBytes = List.from(uploadedImage[i]);
    request.files.add(http.MultipartFile.fromBytes('file[]', selectedFilesBytes, contentType: MediaType('application', 'octet-stream'), filename: files[i].name));
  }

  print("request.files.length");
  print(request.files.length);
  var streamedResponse = await request.send();

  return await http.Response.fromStream(streamedResponse);
} catch (e) {
  print(e);
}

.php

<?php 

 // Count total files
 $countfiles = count($_FILES['file']['name']);
 error_log($countfiles);
 // Looping all files
 for($i=0;$i<$countfiles;$i++){
   $filename = $_FILES['file']['name'][$i];
   
   // Upload file
   move_uploaded_file($_FILES['file']['tmp_name'][$i],'upload/'.$filename);
    
 }

?>

Answered By – minathen

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.