ThinkPHP is a high-performance open-source PHP development framework that comes with powerful file upload capabilities. With proper configuration and implementation, developers can easily meet various file upload requirements. This article provides a step-by-step guide on how to achieve file upload functionality in ThinkPHP.
File upload settings in ThinkPHP are managed in the config.php configuration file. Key configuration items include:
// Default upload driver
'upload_driver' => 'Local',
// Upload file storage path
'upload_path' => '/path/to/upload/folder/',
// Allowed file types for upload
'upload_allow_ext' => 'jpg,png,gif',
// Maximum allowed file size (bytes)
'upload_max_size' => 5242880,
Explanation of each parameter:
Adjustments can be made according to project needs, for example:
'upload_path' => 'public/uploads/',
'upload_allow_ext' => 'jpg,jpeg,png',
'upload_max_size' => 5242880,
A frontend form supporting file upload should be prepared, example below:
<form method="POST" enctype="multipart/form-data" action="{:url('upload')}">
<input type="file" name="file" />
<button type="submit">Upload File</button>
</form>
The enctype="multipart/form-data" attribute is required for file upload forms to ensure data is transmitted in binary format.
Write the file upload handler method in the controller as shown:
namespace app\index\controller;
use think\Controller;
use think\facade\Request;
class Upload extends Controller
{
public function upload()
{
$file = Request::file('file');
// Validate file size and type then move
$result = $file->validate(['size' => 5242880, 'ext' => 'jpg,jpeg,png'])->move('public/uploads/');
if ($result) {
// Upload succeeded
echo 'File upload successful: ' . $result->getSaveName();
} else {
// Upload failed
echo 'File upload failed: ' . $file->getError();
}
}
}
This code fetches the uploaded file, validates size and type, then saves it to the specified directory and returns the result.
With proper configuration and simple code, implementing file upload functionality in the ThinkPHP framework is straightforward. This article covered the configuration file setup, frontend form creation, and backend upload handling process, helping developers quickly master the essentials of file upload development.