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

How to implement the file upload function in ThinkPHP6

WBOY
WBOYOriginal
2023-06-20 08:35:133761browse

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!

Statement:
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