ThinkPHP6 file upload and download: realizing file management and storage
Introduction:
With the rapid development of the Internet, file upload and download have become our One of the essential functions in daily work and life. In the ThinkPHP6 framework, we can upload and download files through simple code to facilitate file management and storage. This article will introduce how to implement file upload and download functions in the ThinkPHP6 framework and provide corresponding code examples.
1. Implementation of the file upload function
<form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="上传" /> </form>
public function upload() { $file = request()->file('file'); $savePath = './uploads/'; // 文件保存路径 // 移动文件到指定位置 $result = $file->move($savePath); if ($result) { // 文件移动成功 echo '文件上传成功'; } else { // 文件移动失败 echo '文件上传失败'; } }
public function upload() { if (request()->isPost()) { $file = request()->file('file'); $savePath = './uploads/'; // 文件保存路径 // 移动文件到指定位置 $result = $file->move($savePath); if ($result) { // 文件移动成功 echo '文件上传成功'; } else { // 文件移动失败 echo '文件上传失败'; } } return $this->fetch(); }
2. Implementation of the file download function
<a href="/download?file=filename">下载文件</a>
public function download() { // 获取要下载的文件路径 $filePath = './uploads/' . input('file'); // 文件下载 if (file_exists($filePath)) { header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($filePath)); header('Content-Length: ' . filesize($filePath)); readfile($filePath); } else { echo '文件不存在'; } }
public function download() { $filePath = './uploads/' . input('file'); if (file_exists($filePath)) { header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($filePath)); header('Content-Length: ' . filesize($filePath)); readfile($filePath); } else { echo '文件不存在'; } }
Conclusion:
Through the above code example, we can see that it is very simple to implement the file upload and download functions in the ThinkPHP6 framework. By mastering this knowledge, we can easily manage and store files and meet users' needs for file upload and download. I hope this article can be helpful to everyone in implementing file upload and download functions.
The above is the detailed content of ThinkPHP6 file upload and download: realize file management and storage. For more information, please follow other related articles on the PHP Chinese website!