1

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

2
  • 3
    Likely because PHP can’t handle multiple parameters with the same name, unless the “syntax” with square brackets is used. Try using file[] as the parameter name. Commented May 11, 2021 at 8:39
  • what is uploadedImage exactly? It's a list and object in one? Commented Oct 25, 2023 at 19:54

1 Answer 1

2

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);
    
 }

?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.