File upload using mysql php in flutter
File upload using mysql php in flutter
1. Set up the MySQL Database
Create a table named files
in your MySQL database to store the file details:
CREATE TABLE files (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
size INT(11) NOT NULL
);
2. Create the PHP Script
Create a PHP file (e.g., upload.php
) on your server to handle the file upload and store the file information in the MySQL database. Here's the complete PHP script:
$servername = "your_servername";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$response = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file'])) {
$file = $_FILES['file'];
$targetDir = "uploads/"; // Set the directory where files will be uploaded
$targetFile = $targetDir . basename($file["name"]);
// Check if file already exists
if (file_exists($targetFile)) {
$response['error'] = true;
$response['message'] = "File already exists.";
} else {
if (move_uploaded_file($file["tmp_name"], $targetFile)) {
$fileName = basename($file["name"]);
$fileSize = $file["size"];
// Insert file details into MySQL database
$sql = "INSERT INTO files (name, size) VALUES ('$fileName', '$fileSize')";
if ($conn->query($sql) === TRUE) {
$response['error'] = false;
$response['message'] = "File uploaded and details saved to database.";
} else {
$response['error'] = true;
$response['message'] = "Error: " . $sql . "
" . $conn->error;
}
} else {
$response['error'] = true;
$response['message'] = "Failed to upload file.";
}
}
} else {
$response['error'] = true;
$response['message'] = "Invalid request.";
}
echo json_encode($response);
$conn->close();
?>
3. Create the Flutter App
Now, let's build the Flutter app that allows users to select a file and send it to the PHP script for uploading. Make sure you have the http
and file_picker
packages installed in your Flutter project.
yaml
dependencies:
flutter:
sdk: flutter
http: ^0.13.3
file_picker: ^4.0.1
Here's the complete Flutter code for the app:
dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:file_picker/file_picker.dart';
class FileUploadScreen extends StatelessWidget {
final String uploadUrl; // Replace with your PHP upload script URL
FileUploadScreen({required this.uploadUrl});
Future
try {
// Create a multipart request for the API
var request = http.MultipartRequest('POST', Uri.parse(uploadUrl));
// Attach the file to the request
request.files.add(http.MultipartFile(
'file',
file.readAsBytes().asStream(),
file.lengthSync(),
filename: file.path.split('/').last,
));
// Send the request
var response = await request.send();
// Check the response status
if (response.statusCode == 200) {
print('File uploaded successfully');
// Handle the success response (if needed)
} else {
print('File upload failed');
// Handle the failure response (if needed)
}
} catch (e) {
print('Error uploading file: $e');
// Handle any errors that occurred during the file upload (if needed)
}
}
Future
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null && result.files.single.path != null) {
File file = File(result.files.single.path!);
_uploadFile(file);
} else {
// User canceled the file picking
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('File Upload'),
),
body: Center(
child: ElevatedButton(
onPressed: () => _pickFile(context),
child: Text('Select and Upload File'),
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'File Upload Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: FileUploadScreen(
uploadUrl: "https://your_server.com/upload.php", // Replace with your PHP upload script URL
),
);
}
}
Replace "https://your_server.com/upload.php"
in FileUploadScreen
with the URL of your upload.php
script on the server.
Ensure that the PHP script is accessible via a public URL and the server hosting the PHP script allows file uploads. Also, make sure the server directory (e.g., "uploads/") where files will be stored has the necessary write permissions.
When the user clicks the "Select and Upload File" button in the Flutter app, it will open a file picker to select the file. Once a file is selected, the app will send it to the PHP script for uploading to the server and storing its details in the MySQL database.
Remember to handle errors and response messages appropriately in both the PHP script and the Flutter app to provide a better user experience. Additionally, consider adding security measures such as file type validation and sanitizing user input to prevent potential security issues.
What's Your Reaction?