-2

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:

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • So, per the error message, `move_uploaded_file` returned false. As per the [documentation](https://www.php.net/manual/en/function.move-uploaded-file.php), if it returns false and no warning was issued (can you confirm that? Do you have warnings enabled? Or have you checked the php log file??) then it means the uploaded file was not valid. I suggest doing some [debugging](https://www.atatus.com/blog/debugging-in-php/) - check the content of `$_FILES` to see what PHP actually received, and if there was an [error code](https://www.php.net/manual/en/features.file-upload.errors.php) given in there. – ADyson Aug 10 '23 at 09:42
  • 1
    _"but the filename is submitting into the database"_ - because you are doing that not only if the move_uploaded_file call succeeded - but also _again_ after this if/else construct, completely independent of whether moving succeeded or not. You should first of all check what $_FILES actually contains, to verify your upload was indeed successful. – CBroe Aug 10 '23 at 09:42
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Aug 10 '23 at 13:06

1 Answers1

1

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;
YaMus
  • 51
  • 5
  • I have tried everything but all in vain. I am posting it to a subdomain "xxxx.xxxx.com". The php file is in subdomain directory like xxxx.xxxx.com/upload.php and the "uploaddata" folder is also in the same directory. I have removed " mkdir('uploaddata', 0777, true); " and also tried with all of them '../uploaddata/'.$files; , './uploaddata/'.$files; , '/uploaddata/'.$files; Nothing is working, still facing the error "File upload failed" in debug console but the path is still printing – Mohammad Ali Aug 10 '23 at 13:39
  • @MohammadAli In that case you need to do the debugging I mentioned in my first comment, above. – ADyson Aug 10 '23 at 13:41
  • @ADyson Thank you for the assistance actually everything was perfect I was writing "temp_name" instead of "tmp_name". I figured out by just debugging as ADyson said and the path was also wrong so I corrected with the help of YaMus. Thanks alot! Happy Coding! – Mohammad Ali Aug 10 '23 at 14:53
  • @YaMus Thank you for the assistance actually everything was perfect I was writing "temp_name" instead of "tmp_name". I figured out by just debugging as ADyson said and the path was also wrong so I corrected with the help of YaMus. Thanks alot! Happy Coding! – Mohammad Ali Aug 10 '23 at 14:53