JQuery Plugin ajaxFileUpload Asynchronous Upload File (PHP version)

Keywords: PHP JQuery

AjaxFileUpload is a good plugin to find, so use it to upload files asynchronously. There are also many articles on the use of the ajaxFileUpload plugin on the Internet, but I find that there is no PHP version, so this time the server side of the process will be handled in PHP language.

1. Explain the grammar parameters of the ajaxFileUpload plugin first

Principle: ajaxfileupload is implemented by listening to iframe's onload method. When processing from the server is complete, the onload event triggering iframe calls its binding method, which obtains the data volume returned by the server in iframe (supported plain text, json,xml,script, html)

Syntax: $.ajaxFileUpload([options])

Parameter description:

urlThe upload handler address, which I send to the server to handle the upload.
fileElementIdThe ID of the file field that needs to be uploaded, that is, <input type="file" id="file">
secureuriWhether to enable secure submission or not, defaults to false.
dataTypeThe data type returned by the server. Can be xml,script,json,html. If not filled in, jQuery will automatically determine.
successThe parameter data is the data returned by the server.
errorA handler that fails to automatically execute.
dataCustom parameters. This is useful, for example, if you upload a picture and want to transfer the name of the picture, you can use this parameter to achieve.
typeWhen submitting a custom parameter, this parameter is set to post

2. Next let's see how to use it

1. Introduce ajaxFileUpload as a plugin first.

<script src="jquery-1.11.1.js" type="text/javascript"></script>
<script src="ajaxfileupload.js" type="text/javascript"></script>

I'm using jq1.11.1 here. There are online statements that the JQ version should correspond to the version of ajaxfileupload so that there will be no abnormal error, but I am right now.

2. Paste HTML code.

<div data-role="fieldcontain" class="upload-box">
    <label for="id_photos"><span class="red">* </span>Your valid certificate:</label>
    <input type="file" id="id_photos" name="id_photos" value="upload" style="filter:alpha(opacity=10);-moz-opacity:10;opacity:10;" />            
    <p style="margin-top:0.5em;color:#999;Font-size:11pt;">Instructions: Please upload a half-body photo of your handheld certificate. Make sure that the certificate information in the photo is clear and readable. </p>
<div class="id_photos" ></div>

The main thing here is the code <input type="file" id="id_photos" name="id_photos" value="upload">whatever else, because here I'm on the phone, using the jqueryMobile plug-in.

3. Processing to js code.

$(document).bind('pageinit', function(){
    //Photo Asynchronous Upload
    $('#id_photos').change(function(){//Change event is used here, triggered when the selected picture opens and the window closes
        url:'/uploader/',   //Script path for processing pictures
        type: 'post',       //Mode of submission
        secureuri :false,   //Is Secure Submission Enabled
        fileElementId :'id_photos',     //file Control ID
        dataType : 'json',  //Data type returned by server      
        success : function (data, status){  //Processing functions that execute automatically after a successful submission
            if(1 != data.total) return;   //Since this means that you are allowed to upload a leaflet picture, if the number is not 1, there is an error.
            var url = data.files[0].path;  
            //The effect here is that when uploaded successfully, a json data is returned with the url inside, the url is given to the img tag, and then appended to the.id_photos class to display the picture
            $('.id_photos').append('<img src="'+url+'" value="'+url+'" style="width:80%" >');
        error: function(data, status, e){   //Handling function for automatic execution of commit failures

Here I've basically commented on each line of code to make it easier for you to understand. The process is to upload a picture to uploader.php, process it and successfully return the JSON data, then take out the url value in json, assign it to the img tag, and append the IMG tag with the page to display.

Here I attach the data returned by json:

    "total": 1,
    "success": 1,
    "files": [
            "srcName": "3.jpg",
            "error": 0,
            "size": 10715,
            "type": "image/jpeg",
            "success": true,
            "path": "http://m.kellyblog.com/upload/20150528/857f4a35664b4a665e713322306d73b2.0x124x126.jpg",
            "width": 124,
            "height": 126


The HTML page before uploading looks like this:

The HTML page looks like this when the asynchronous upload succeeds:


4. How PHP is handled

class UploaderController extends XXXX_Controller {
    public function index() {
        $files = array();
        $success = 0;    //User counts how many pictures were successfully uploaded

        foreach ($_FILES as $item) {
            $index = count($files);

            $files[$index]['srcName'] = $item['name'];    //Original name of uploaded picture
            $files[$index]['error'] = $item['error'];    //Error code associated with uploading this file
            $files[$index]['size'] = $item['size'];        //Uploaded file size in bytes
            $files[$index]['type'] = $item['type'];        //The MIME type of the file, which requires browser support, such as "image/gif"
            $files[$index]['success'] = false;            //This is used to mark whether the picture was successfully uploaded
            $files[$index]['path'] = '';                //Save Picture Path

            // Is there an error in the receive process
            if($item['error'] != 0) continue;
            //Determine if pictures can be uploaded
            if(!is_uploaded_file($item['tmp_name'])) {
                $files[$index]['error'] = 8000;
            $extension = '';
            if(strcmp($item['type'], 'image/jpeg') == 0) {
                $extension = '.jpg';
            else if(strcmp($item['type'], 'image/png') == 0) {
                $extension = '.png';
            else if(strcmp($item['type'], 'image/gif') == 0) {
                $extension = '.gif';
            else {
                //If the type is not one of the above three, we will intercept the original name of the picture to make a judgment (rigorous)
                $substr = strrchr($item['name'], '.');
                if(FALSE == $substr) {
                    $files[$index]['error'] = 8002;

                //After obtaining the extension of the metaname, assign the corresponding value to the type by the extension
                if(strcasecmp($substr, '.jpg') == 0 || strcasecmp($substr, '.jpeg') == 0 || strcasecmp($substr, '.jfif') == 0 || strcasecmp($substr, '.jpe') == 0 ) {
                    $files[$index]['type'] = 'image/jpeg';
                else if(strcasecmp($substr, '.png') == 0) {
                    $files[$index]['type'] = 'image/png';
                else if(strcasecmp($substr, '.gif') == 0) {
                    $files[$index]['type'] = 'image/gif';
                else {
                    $files[$index]['error'] = 8003;
                $extension = $substr;

            //Encrypt temporary file names for later complex new file names
            $md5 = md5_file($item['tmp_name']);
            //Get the size of the picture
            $imageInfo = getimagesize($item['tmp_name']);
            $rawImageWidth = $imageInfo[0];
            $rawImageHeight = $imageInfo[1];

            //Set the upload path for pictures and place them in the upload folder to generate folder classified storage for month, month and year.
            //rtrim(base_url(),'/') is actually the root directory of the website, you can handle it yourself
            $path = rtrim(base_url(), '/') . '/upload/' . date('Ymd') . '/';
            //Make sure the directory is writable
            //file name
            $name = "$md5.0x{$rawImageWidth}x{$rawImageHeight}{$extension}";
            //Add picture file does not change, that is, there is no need to duplicate upload, there is no upload
            $ret = file_exists($path . $name) ? true : move_uploaded_file($item['tmp_name'], $serverPath . $name);
            if($ret === false) {
                $files[$index]['error'] = 8004;
            else {
                $files[$index]['path'] = $path . $name;        //Save Picture Path
                $files[$index]['success'] = true;            //Picture upload success logo
                $files[$index]['width'] = $rawImageWidth;    //image width
                $files[$index]['height'] = $rawImageHeight;    //Picture Height
                $success ++;    //Success+1

        //Return the picture as a json to the js processing page, where you can change your json return processing code
        echo json_encode(array(
            'total' => count($files),
            'success' => $success,
            'files' => $files,
//Here I enclose the code for the ensure_writable_dir() function
* Make sure the folder exists and is writable
* @param string $dir
function ensure_writable_dir($dir) {
    if(!file_exists($dir)) {
        mkdir($dir, 0766, true);
        chmod($dir, 0766);
        chmod($dir, 0777);
    else if(!is_writable($dir)) {
        chmod($dir, 0766);
        chmod($dir, 0777);
        if(!is_writable($dir)) {
            throw new FileSystemException("Catalog $dir Unwritable");

The code is basically commented to make it easier for you to understand. Although PHP is used to process picture upload, you understand the logic of the program code when uploading, and you can use it in.net or java.

This is the entire analysis process of asynchronously uploading files using the JQuery plug-in ajaxFileUpload.

Posted by elie on Mon, 13 Sep 2021 17:11:59 -0700