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