Backend Development 5 min read

Implementing Ajax Image Upload with Deletion in ThinkPHP5

This guide demonstrates how to replace a standard file upload in a ThinkPHP5 post feature with an Ajax-based solution that allows real‑time image preview, server‑side handling via PHP, and selective deletion of uploaded images, improving compatibility and user experience.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Implementing Ajax Image Upload with Deletion in ThinkPHP5

While learning ThinkPHP5, a post feature required a topic image selector; using the native file upload works but introduces many compatibility issues, so an Ajax approach is adopted to enable selective deletion without such problems.

Form markup used for the upload:

<form method="post" enctype="multipart/form-data">
<div style="margin: 20px 20px 20px 10px;">
    主题图片:
    <span id="img-list-box" style="margin-left: 25px;"></span>
    <span style="display:inline-block;height: 30px;position: relative;top:0px;left:0px;">
        <a style="display: inline-block;width: 100px;height:30px;line-height: 30px;text-align:center;background: #F60;color: #FFF;">图片上传</a>
        <input type="file" name="img_src" style="width: 100px;border: 1px solid red;position: absolute;top:0px;left: 0px;height: 30px;opacity: 0;" id="up-img-file" onchange="upimg(this)">
    </span>
</div>
</form>

Since a regular form cannot meet the Ajax requirements, a click event is bound to the upload button to trigger image selection and Ajax upload.

JavaScript handling:

<script type="text/javascript" src="__STATIC__/home/js/jquery.min.js"></script>
<script type="text/javascript">
    function upimg(obj) {
        if (obj.value == "") { return; }
        var formdata = new FormData();
        formdata.append("img", $(obj)[0].files[0]); // get file
        $.ajax({
            type: 'post',
            url: '/home/note/upimg', // API endpoint
            data: formdata,
            cache: false,
            processData: false, // do not process FormData
            contentType: false, // do not set content type header
            success: function(response) {
                console.log(response);
                var html = '<p style="position: relative;margin-right: 20px;margin-bottom: 15px;width: 132px;display: inline-block;border: 1px solid #CCC;background:#EEE;">'
                        +'<span style="display: block;width: 120px;height: 80px;border: 1px solid #F2F1F0;margin: 5px;overflow: hidden;">'
                        +'<img src="' + response + '" style="width: 100%;" />'
                        +'</span>'
                        +'<input type="hidden" name="imgs[]" value="' + response + '" />'
                        +'<a onclick="delImg(this);" style="z-index: 10;display: block;top: -8px;cursor:pointer;right: -8px;position:absolute;width: 20px;height: 20px;background: #CCC;border-radius:100%;text-align:center;line-height: 20px;border: 1px solid #C1C1C1;color: #555;">X</a>'
                        +'</p>';
                $('#img-list-box').append(html);
            },
            error: function() { }
        });
    }
    function delImg(obj) {
        $(obj).parent('p').remove();
    }
</script>

On the server side, the PHP method processes the uploaded file, moves it to the public uploads directory, and returns the image path for the Ajax response:

public function upimg()
{
    // Validate
    $file = request()->file('img');
    // Move to /public/uploads/
    if ($file) {
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if ($info) {
            $img_src = '/uploads/' . $info->getSaveName();
            echo $img_src; // return to Ajax
        } else {
            $this->error($file->getError());
        }
    }
}

After integration, the uploaded image appears with a delete button, providing a smoother user experience without page reloads.

JavaScriptPHPAJAXImage UploadFormDataThinkPHP5
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.