Home PHP Framework ThinkPHP How to implement the file upload function in ThinkPHP6

How to implement the file upload function in ThinkPHP6

Jun 20, 2023 am 08:35 AM
thinkphp File Upload accomplish

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'], //子目录名称的命名规则
],
Copy after login

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);
}
Copy after login

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>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

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.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

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? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

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

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

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.

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

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

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

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 use gRPC to implement file upload in Golang? How to use gRPC to implement file upload in Golang? Jun 03, 2024 pm 04:54 PM

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.

Simplify file upload processing with Golang functions Simplify file upload processing with Golang functions May 02, 2024 pm 06:45 PM

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.

See all articles