Search code examples
phpflutterdioflutter-packagesfilepicker

Unable to save/upload files to a folder on server with Dio and File_picker flutter packages & I am doing this with PHP


The problem I am facing is that the files I upload ta server are not being uploaded inside a folder but the filename is submitting into the database. I am providing all data related to selecting a file and then uploading it to the server

My flutter code is:

Dio dio = Dio(); // Initialize Dio instance
String? filePath;

Future<String> getFile() async {
  FilePickerResult? file = await FilePicker.platform.pickFiles(
    type: FileType.custom,
    allowedExtensions: ['pdf', 'docx', 'jpeg'],
  );

  if (file != null && file.files.isNotEmpty) {
    List<String> paths = file.files.map((file) => file.path!).toList();
    print("Selected file paths: $paths");
    return paths[0]; // Return the first selected file path
  }
  return ''; // Return an empty string if no file is selected
}

Future<void> _uploadFile(String filePath) async {
  if (filePath.isNotEmpty) {
    String originalFileName = basename(filePath);
    String randomFileName =
        '${DateTime.now().millisecondsSinceEpoch}_$originalFileName';

    FormData formData = FormData.fromMap({
      "file":
          await MultipartFile.fromFile(filePath, filename: randomFileName),
    });

    try {
      Response response = await dio.post(
        "path-to-my-file-uploading-php-code",
        data: formData,
      );
      print("file upload response status code: ${response.statusCode}");
      print("file upload response data: ${response.data}");
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('File Uploaded!')),
      );
    } catch (e) {
      print("exception caught: $e");
    }
  } else {
    print("No file selected.");
  }
}

This is the UI for selecting and submitting file:

    Center(
     child: ElevatedButton(
     onPressed: () async {
      String filePath =
          await getFile(); // Get the selected file path
      if (filePath.isNotEmpty) {
        _uploadFile(
            filePath); // Call the _uploadFile function with the file path
      } else {
        print("No file selected.");
      }
    },
    child: Text('SUBMIT FORM'),
    style: ElevatedButton.styleFrom(
        minimumSize: Size(150, 50),
        primary: Color(0xffcc493f),
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.zero)),
     ),
    ),

This is my PHP code for uploading file to the folder:

        <?php 

        $db = mysqli_connect('localhost','database-username','database-password','database');
        if(!$db){
            echo "Database connection failed!";
        }

        if (!file_exists('uploaddata')) {
            mkdir('uploaddata', 0777, true); // Create folder with full permissions recursively
        }

        $files = $_FILES['file']['name'];

        $file_path = '../uploaddata/'.$files;
        $temp_name = $_FILES['file']['temp_name'];

        if (move_uploaded_file($temp_name, $file_path)) {
            // File moved successfully, proceed with database insertion
            $db->query("INSERT INTO filesupload(files) VALUES('".$files."')");
        } else {
            echo "File upload failed.";
        }
        echo "File path: " . $file_path;

        $db->query("INSERT INTO filesupload(files)VALUES('".$files."')");

        ?>

The attachment file indicating the error I am receiving in Debug Console:


Solution

  • You creating folder on current path mkdir('uploaddata', 0777, true); and trying move uploaded file to one folder up.

    So try change

    $file_path = '../uploaddata/'.$files;
    

    to

    $file_path = './uploaddata/'.$files;