How to implement the file upload function in ThinkPHP6
With the continuous development of the Internet, more and more websites need to implement file upload functions. In ThinkPHP6, it is also very simple to implement the file upload function. Today we will introduce how to implement the file upload function in ThinkPHP6.
1. Configure file upload parameters
Before starting to implement the file upload function, you first need to set the file upload parameters in the ThinkPHP6 configuration file. Find the project configuration file config/app.php, and then add the following code in the params array:
'upload' => [ 'maxSize' => 1024 * 1024 * 10, //文件上传的最大大小 'exts' => ['jpg', 'gif', 'png', 'jpeg'], //允许上传的文件后缀 'rootPath' => app()->getRootPath() . 'public/uploads/', //文件上传的根目录 'savePath' => '', //文件保存的子目录 'subName' => ['date', 'Ymd'], //子目录名称的命名规则 ],
Here we set the maximum file upload size to 10MB, and the file suffixes allowed to be uploaded are jpg, gif, and png. , jpeg four formats, the root directory for file upload is public/uploads/, and the naming rule for subdirectories is set to be named by date (year, month, day).
2. Implement the file upload function
After configuring the file upload parameters, you can start to implement the file upload function. Write the following code in the controller:
public function upload() { $file = request()->file('image'); if ($file) { $info = $file->validate(['ext' => 'jpg,png,gif,jpeg'])->move(config('upload.rootPath')); if ($info) { $data = [ 'code' => 0, 'msg' => '上传成功', 'url' => config('upload.rootPath') . $info->getSaveName(), ]; } else { $data = [ 'code' => 1, 'msg' => $file->getError(), 'url' => '', ]; } } else { $data = [ 'code' => 1, 'msg' => '请选择要上传的文件', 'url' => '', ]; } return json($data); }
Here we first obtain the uploaded file through the request()->file('image') method to determine whether the file exists; then use the validate() method to verify the upload Verify the file suffix to ensure that the file format uploaded by the user is correct; finally use the move() method to upload the file and return the result of successful upload or failed upload.
3. Page implementation
Finally, we need to implement the file upload function on the page. The code is as follows:
<form id="upload-form" action="<?php echo url('upload'); ?>" method="post" enctype="multipart/form-data"> <input type="file" name="image" id="image" accept="image/jpeg,image/png,image/gif"> </form> <button id="btn-upload" type="button">上传</button> <script> $(function() { $('#btn-upload').click(function() { var formData = new FormData($('#upload-form')[0]); $.ajax({ url: $('#upload-form').attr('action'), type: 'post', data: formData, contentType: false, processData: false, success: function(res) { if (res.code === 0) { alert(res.msg); $('#image').val(''); } else { alert(res.msg); } }, error: function(xhr, status, error) { alert('上传错误:' + error); } }); }); }); </script>
Here we add a form form to the page to upload The name value of the input tag of the file is 'image', and then use jQuery's ajax() method to upload the form data to the controller in FormData mode, and prompt accordingly after the upload is successful or failed.
4. Summary
Through the above code implementation, we have successfully implemented the file upload function in ThinkPHP6. At the same time, we must also pay attention to security, ensure that the files uploaded by users are in the correct format and size, avoid uploading files from causing harm to the system, and ensure the security of users and the system.
The above is the detailed content of How to implement the file upload function in ThinkPHP6. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

How to implement file upload using gRPC? Create supporting service definitions, including request and response messages. On the client, the file to be uploaded is opened and split into chunks, then streamed to the server via a gRPC stream. On the server side, file chunks are received and stored into a file. The server sends a response after the file upload is completed to indicate whether the upload was successful.

Answer: Yes, Golang provides functions that simplify file upload processing. Details: The MultipartFile type provides access to file metadata and content. The FormFile function gets a specific file from the form request. The ParseForm and ParseMultipartForm functions are used to parse form data and multipart form data. Using these functions simplifies the file processing process and allows developers to focus on business logic.
