Home  >  Article  >  PHP Framework  >  How to use ThinkPHP6 to upload images

How to use ThinkPHP6 to upload images

王林
王林Original
2023-06-20 21:25:413075browse

With the development of the Internet, image uploading has become an essential function in website and application development. In the field of PHP, ThinkPHP6 has become a very popular development framework. In this article, we will introduce how to use ThinkPHP6 to implement image upload.

1. Create project and controller

First, we need to create a new ThinkPHP6 project. You can use Composer to install it, or you can download the latest version from the official website.

After the installation is complete, enter the directory where the project is located in the console and use the following command to create a new controller:

php think make:controller Upload

This will create a new controller named Upload in the /app/controller directory controller.

2. Write code

Next, we need to write code in the controller to upload images. The following is a basic code example:

namespace appcontroller;

use thinkController;
use thinkacadeRequest;

class Upload extends Controller
{
    public function index()
    {
        return view();
    }

    public function upload()
    {
        $file = Request::file('image');

        $info = $file->validate(['size'=>5242880,'ext'=>'jpg,png,gif'])->move( './uploads');
        
        if($info){
            return json(['code'=>200,'msg'=>'上传成功','url'=>$info->getSaveName()]);
        }else{
            return json(['code'=>500,'msg'=>$file->getError()]);
        }
    }
}

In the above code, we first use the use statement to import the Request class. This class will help us obtain the files uploaded by the user. Then, we define a method called upload, which will be used to handle upload requests. We used the Request::file function to obtain the file uploaded by the user, verified the file size and file type, and then saved the file to the ./uploads directory. Finally, we return the results to the frontend in JSON format.

3. Front-end page

Finally, we need to create a front-end page to realize the function of users uploading files. The following is a basic HTML code example:

<form id="image-form" enctype="multipart/form-data">
    <input type="file" name="image">
    <input type="submit" value="上传">
</form>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
    $('#image-form').submit(function(event) {
        event.preventDefault();
        var formData = new FormData($(this)[0]);
        $.ajax({
            url: '/upload/upload',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.code === 200) {
                    alert('上传成功');
                    console.log(data.url);
                } else {
                    alert('上传失败:' + data.msg);
                }
            },
            error: function () {
                alert('上传失败');
            }
        });
    });
});
</script>

In the above code, we create a form and associate it with the upload method of the Upload controller on the server using JavaScript code. After the user selects the file to upload and clicks the "Upload" button, the browser will submit the file and other form data to the server in the form of FormData. After the server obtains the file through the $request->file function, it can process the file and then return the processing result to the front end in JSON format.

4. Summary

So far, we have completed a simple image upload function by using ThinkPHP6 and JavaScript code. Of course, this is just a basic implementation. To implement more complex image upload functions, you need to have an in-depth understanding of server technology and front-end libraries. Hope this article helps you!

The above is the detailed content of How to use ThinkPHP6 to upload images. 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