-1

I want to submit form which contains files and textformfield data. First I select the files from phone, in debug console I can see the path of the selected files but it is in cache like this:

"Selected file paths: [/data/user/0/com.example.nexgen_app/cache/file_picker/images (1).jpeg, /data/user/0/com.example.nexgen_app/cache/file_picker/images.jpeg]".

Now after selecting the files, I want to send these files to a folder on my server along with other textformfield data which is inserted into database and I am doing this with PHP code that is saved in a file on my server.

This is the logic I am using to select files and then upload them into a folder on my server's path "path-to-php-file-for-uploading-files":

Future<void> _pickFiles() async {
  FilePickerResult? result = await FilePicker.platform.pickFiles(
    allowMultiple: true,
    type: FileType.custom,
    allowedExtensions: ['jpeg', 'pdf', 'doc', 'docx', 'ppt', 'pptx'],
  );

  if (result != null && result.files.isNotEmpty) {
    List<String> paths = result.files.map((file) => file.path!).toList();
    selectedFiles.value = paths;
    print("Selected file paths: $paths");
  }
}

void submitForm() async {
  List<String> selectedFilePaths = selectedFiles.value;
  if (selectedFilePaths.isEmpty) {
    print('No file selected. Cannot submit form.');
    return;
  }

  final APIURL = Uri.parse(
      "path-to-php-file-for-uploading-files");
  var request = http.MultipartRequest("POST", APIURL);

  request.files.add(await http.MultipartFile.fromPath('filesuploaddata', selectedFilePaths[0]));
  request.fields['selected_date'] = _selectedDate!.toLocal().toString().split(' ')[0];
  request.fields['affiliateeferrer'] = affiliateReferrer.text;
  ...
  ...
  ...


  try {
    var response = await request.send();
    if (response.statusCode == 200) {
      String responseBody = await response.stream.bytesToString();
      print('Response Body: $responseBody');
      ScaffoldMessenger.of(context)
          .showSnackBar(const SnackBar(content: Text('Form Submitted!')));
    } else {
      print('File upload failed with status: ${response.statusCode}');
      print('Server Response: ${await response.stream.bytesToString()}');
    }
  } catch (e) {
    print('Error uploading file: $e');
  }
}

This is my UI code for selecting files:

GestureDetector(
onTap: _pickFiles,
child: Padding(
padding: EdgeInsets.symmetric(vertical: 10.0),
child: DottedBorder(
radius: Radius.circular(10),
borderType: BorderType.RRect,
dashPattern: [10, 4],
strokeCap: StrokeCap.round,
color: Colors.grey.shade600,
child: Container(
  width: double.infinity,
  height: 150,
  decoration: BoxDecoration(
      color: Color(0xffe5e8e8),
      borderRadius:
          BorderRadius.circular(10)),
  child: Column(
    mainAxisAlignment:
        MainAxisAlignment.center,
    children: [
      Icon(
        Iconsax.folder_open,
        color: Colors.grey.shade800,
        size: 40,
      ),
      SizedBox(
        height: 15,
      ),
      Text(
        'File Upload',
        style: TextStyle(
            fontSize: 15,
            color: Colors.grey.shade400),
      ),
      Text(
        'You can upload up to 5 files',
        style: TextStyle(
            fontSize: 15,
            color: Colors.grey.shade400),
      ),
      ValueListenableBuilder<List<String>>(
        valueListenable: selectedFiles,
        builder: (context, files, child) {
          if (files.isNotEmpty) {
            return Text(
              'Number of selected files: ${files.length}',
              style: TextStyle(
                  fontSize: 15,
                  color:
                      Colors.grey.shade600),
            );
          } else {
            return Container();
          }
        },
       ),
      ],
     ),
    ),
   )),
  ),

This one is for submitting the form:

    Center(
     child: ElevatedButton(
      onPressed: () {
       if (_formKey.currentState!.validate()) {
        submitForm();
        _formKey.currentState!.reset();
        scrollController.animateTo(
          0.0, // Step 3: Scroll to top
          duration: Duration(milliseconds: 500),
          curve: Curves.easeInOut);
       }
     },
    child: Text('SUBMIT FORM'),
    style: ElevatedButton.styleFrom(
    minimumSize: Size(150, 50),
    primary: Color(0xffcc493f),
    shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.zero)),
   ),
  ),

And this is my PHP code which is working fine but not receiving the files, instead textformfield data is received by this code and inserted into the database:

$servername = "localhost";
$database = "db-name";
$username = "db-username";
$password = "db-pass";

// Create a connection to MySQL
$conn = mysqli_connect($servername, $username, $password, $database);

if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}

$affiliateReferrer = $_POST['affiliatereferrer'];

];

    $targetDirectory = $serverPath . "../uploaddata/";
    $responseData = array();
    $fileFieldName = "filesuploaddata";
    
    if (!chmod($targetDirectory, 0777)) {
        echo "Failed to set permissions for the 'uploaddata' folder.";
        // Handle the error gracefully based on your requirements.
    }
    
    foreach ($_FILES[$fileFieldName]['tmp_name'] as $index => $tmpName) {
        $fileName = $_FILES[$fileFieldName]['name'][$index];
        $filePath = $targetDirectory . $fileName;
    
        if (move_uploaded_file($tmpName, $filePath)) {
            echo "File $fileName was successfully uploaded and saved<br>";
        } else {
            echo 'Error moving uploaded file: ' . $_FILES[$fileFieldName]['error'][$index] . "    <br>";
        }
    }


  $query = "INSERT INTO form_submit_nexgen (sent_commission_type, ... , ... )VALUES('$selectedValue', ... ... )";

  if ($conn->query($query) === TRUE) {
  echo 'Form data submitted successfully';
  } else {
  echo 'Error: ' . $query . '<br>' . $conn->error;
  }

  $conn->close();
  • **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 06 '23 at 21:12
  • What does it mean ? Is this really gonna help me ? And how can I do that ? Please be specific and clear because I want to sort it out asap. – Mohammad Ali Aug 07 '23 at 11:03
  • Which part did you not understand? It looks like you are using some really bad tutorial. I highly encourage you to find something better. If you are only starting to learn PHP then you should learn PDO instead of mysqli. PDO is much easier and more suitable for beginners. Start here https://phpdelusions.net/pdo & https://websitebeaver.com/php-pdo-prepared-statements-to-prevent-sql-injection. Here are some good video tutorials https://youtu.be/2eebptXfEvw & https://www.youtube.com/watch?v=sVbEyFZKgqk&list=PLr3d3QYzkw2xabQRUpcZ_IBk9W50M9pe- – Dharman Aug 07 '23 at 11:15
  • I have to submit a form to a Wordpress website database and it uses mySQL. I am a flutter newbie! Can you please tell me if my PHP code is bad or my flutter code is bad? – Mohammad Ali Aug 07 '23 at 11:18
  • I don't know flutter, but your PHP code is terrible. Not your fault because you've been learning from bad tutorials. – Dharman Aug 07 '23 at 11:52

0 Answers0