Home > PHP Framework > ThinkPHP > body text

Detailed explanation of how thinkPHP uses ajax to asynchronously upload images and display and delete them

藏色散人
Release: 2021-03-23 13:43:30
forward
2319 people have browsed it

The following tutorial column will introduce to you how thinkPHP uses ajax to asynchronously upload images and display and delete them. I hope it will be helpful to friends in need! thinkPHP uses ajax to asynchronously upload pictures and display and delete them

In the process of learning tp5 recently, there is a posting function in the project to select theme pictures. As follows:

# Using the original file upload processing, although the uploaded image can be displayed in real time through the original js statement, this will involve many compatibility issues. Use ajax technology to realize the function of selectively deleting selected pictures without compatibility issues.

Detailed explanation of how thinkPHP uses ajax to asynchronously upload images and display and delete them

Form file form:

Copy after login
    主题图片:                   图片上传               
If we need to send an Ajax request, of course the form cannot meet our needs. Therefore, we need to associate a click event with the form to help us Make an Ajax request and select an image.
When we click the upload image button, the image selection is triggered to implement Ajax upload.

JavaScript code:

Copy after login

After clicking to select the image, it is handed over to the server for processing. php interface file:

    public function upimg()
    {
        //验证
        $file = request()->file('img');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                // 成功上传后 获取上传信息
                $img_src = '/uploads/'.$info->getSaveName();
                echo $img_src; //返回ajax请求
            }else{
                // 上传失败获取错误信息
                $this->error($file->getError());
            }
        }
    }
Copy after login
Improved renderings:


The above is the detailed content of Detailed explanation of how thinkPHP uses ajax to asynchronously upload images and display and delete them. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!