ThinkPHP+JQuery for asynchronous file upload

Front-end code

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>ThinkPHP+JQuery Asynchronous upload of files</title>
</head>
<body>

<form id="ajax-upload-demo" enctype="multipart/form-data">
    <label>Select File:</label>
    <input type="file" name="image"><br><br>
    <a href="javascript:uploadFile();">upload</a>
</form>
<br><p id="tips"></p>

<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script>

    var isUploading = false;

    // Upload files
    function uploadFile(){
        var form = document.getElementById('ajax-upload-demo');
        if(isUploading) {
            alert('File is being uploaded...');
            return false;
        }
        $.ajax({
            url: '/index/index/uploadApi',
            type: 'POST',
            cache: false,
            data: new FormData(form),
            processData: false,
            contentType: false,
            dataType: 'json',
            beforeSend: function () {
                isUploading = true;
            },
            success: function (json) {
                var arr = JSON.parse(json);
                if(arr.errcode == 10000){
                    // Upload success
                    alert('Upload success');
                    var url = arr.data.url;
                    var tips = "<a href='" + url + "' target='_blank'>Click to view</a>";
                    $("#tips").empty().append(tips);

                }else{
                    // Upload failure
                    alert('Upload failure');
                }
                isUploading = false;
            }
        });
    }
</script>
</body>
</html>

Design sketch:

PHP code

<?php
namespace app\index\controller;

use think\Controller;

class Index extends Controller
{
    // Upload form page
    public function index()
    {
        return $this->fetch();
    }

    // Upload file interface
    public function uploadApi(){
        // get files
        $file = request()->file('image');
        if($file){
            // Check array
            $validateArr = [ 'ext' => 'jpg,jpeg,gif,png,bmp' ];
            // Local storage path for the file
            $path = ROOT_PATH . 'public' . DS . 'upload';
            // Verify and move
            $info = $file->validate($validateArr)->move($path);
            // Check movement results
            if($info){
                // Upload success

                // Output jpg
                #echo $info->getExtension();

                // Output 20160820 / 42a797759f284b767dfcb2a019794287.jpg
                #echo $info->getSaveName();

                // Output 42a797759f284b767dfcb2a0197904287.jpg
                #echo $info->getFilename();

                // Original file name of the file
                $sourceInfo = $info->getInfo();
                $sourceName = $sourceInfo['name'];

                // Assembling url
                $url = '/upload/'.$info->getSaveName();
                $url = str_replace('\\', '/', $url); // Replace path separator under Windows

                // other some operations ...

                // Return json and tell the client to upload the result
                $json = json_encode([
                    'errcode'   => '10000',
                    'errmsg'    => 'Upload success',
                    'data'      => [ 'url' => $url ]
                ]);
            }else{
                // Upload failed, return json and inform the client
                $json = json_encode([
                    'errcode'   => '20002',
                    'errmsg'    => 'Upload failed',
                ]);
            }
        }else{
            // File not uploaded
            $json = json_encode([
                'errcode'   => '20001',
                'errmsg'    => 'File not uploaded',
            ]);
        }
        return $json;
    }
}

Upload test

1. Upload a picture

2. Upload succeeded

3. Click to view

4. View pictures

5. View the upload directory

Possible errors

1. PHP upload restrictions

Solution
Open PHP configuration file php.ini

  1. Find Max execution time and change the value to 60 or greater
  2. Find post_max Zise and change the value to 128M or greater
  3. Find the upload? Max? Filesize and change the value to 128M or greater

Reason

  1. Max execution time is the maximum number of execution seconds for a request. If the upload file is too large, the server may end the program before receiving the file;
  2. post_max_size refers to the maximum size allowed by POST data;
  3. Upload? Max? Filesize refers to the maximum size of the uploaded file.

Link to this article: https://www.cnblogs.com/connect/p/thinkphp-ajax-upload.html

Tags: PHP JSON JQuery Javascript

Posted on Wed, 04 Dec 2019 15:09:13 -0500 by sactown