Uploading multiple files – jquery+php

Strategy:

  • Initiate 3 file input box, put Add button on top of the form to add more file input box dynamically.
  • Using ajax to upload files to the server for processing in batch.
  • When page first loaded, show existing images, when upload files completed refresh all images.
  • Long-press the image to popup delete confirmation window to confirm for image deletion.

Uploading multiple files - jquery+php

Coding:

HTML form
<form id="uploadForm" method="post">
  <div class="left">上传图片 <img id="add-more" src="img/add.png" /></div>
  <div class="right"><input class="btnSubmit" type="submit" value="开始上传" /></div>
  <div id="input">
  <div class="fileblock"><input type="text" id="label1" placeholder="文件名称" /><input name="userImage[]" type="file" class="inputFile" /></div>
  <div class="fileblock"><input type="text" id="label2" placeholder="文件名称" /><input name="userImage[]" type="file" class="inputFile" /></div>
  <div class="fileblock"><input type="text" id="label3" placeholder="文件名称" /><input name="userImage[]" type="file" class="inputFile" /></div>
  </div>
  <div id='msg'>&nbsp;</div>
  <div id="gallery">目前还没有上传图片。</div>
</form>
Javascript

set variables for new file input box, and file identity.
 var i = 3;
 var id = getParameterByName('id');
 var id_type = getParameterByName('idtype')
Adding file input box (js):

$("#add-more").on('click',()=>{
   $("#input").append('<div class="fileblock"><input type="text" id="label'+ ++i+'" placeholder="文件名称" /><input name="userImage[]" type="file" class="inputFile" /></div>');
});
Upload files (js)

$("#uploadForm").on('submit',function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    formData.append('id',id);
    formData.append('id_type',id_type);
    for(k=1;k<i+1;k++){
        formData.append('label'+k, $("#label"+k).val());
    }
    $.ajax({
        url: serviceLocation+"/api/upload-files.php",
        type: "POST",
        dataType: 'text',  // what to expect back from the PHP script, if anything
        data:  formData,
        contentType: false,
        cache: false,
        processData:false,
        success: function(data){
            $US.showImages();
        },
        error: function (xhr, status, thrownError) { $US.showError('msg', xhr.responseText); }
    });
});
Server side process (php)

if(is_array($_FILES)) {
    $errors= array();
    $i=1;
    $response = "";

    foreach ($_FILES['userImage']['name'] as $name => $value){
        $label = $_POST["label$i"];
        if($label=='')$label = $_FILES['userImage']['name'][$name];
        $i++;

        if(is_uploaded_file($_FILES['userImage']['tmp_name'][$name])) {
            $file_name = $_FILES['userImage']['name'][$name];
            $file_size = $_FILES['userImage']['size'][$name];
            $file_tmp  = $_FILES['userImage']['tmp_name'][$name];
            $file_type = $_FILES['userImage']['type'][$name];
            $file_ext  = strtolower(end(explode('.',$_FILES['userImage']['name'][$name])));

            $year = date("Y");
            $month = date("m");
            $file_path = "uploads/$year/$month/$file_name";

            $uservice = new uservice($conn);
            $res = $uservice->saveFileInfo($id_type,$id,$label,$file_path,'file',$file_size,$file_ext);

            if($res!==true)
                $errors[$i] = "数据库出错。";
            else if(empty($errors)===true){
                $res = move_uploaded_file($file_tmp,"../$file_path");
                if($res!==true) $errors[$i] = "文件保存失败。";
            }
        }
    }
    
    if(empty($errors)===true){
        echo '{"status":"ok","data":"文件已保存。"}';
    }
    else echo '{"status":"error","msg":"文件保存失败。"}';
}
Show images

var timer;
var $US = {
    file_id:[],
    showImages: function(){
        if(id_type=='' || id=='') return;
        
        var form = new FormData();
        form.append('id_type',id_type);
        form.append('id',id);
        $.ajax({
            url: serviceLocation+"/api/get-files.php",
            type: "POST",
            dataType: 'text',  // what to expect back from the PHP script, if anything
            data:  form,
            contentType: false,
            cache: false,
            processData:false,
            success: function(data){
                if(typeof data == 'string') data = JSON.parse(data);
                
                var touchstart = 'mousedown';
                var touchend = 'mouseup';
                
                var box = $("#gallery")
                if(data.length>0){
                    box.html('');
                    $.each(data,(e,v)=>{
                        $US.file_id.push(v.file_id);
                        var imgUrl = serviceLocation+v.path;
                        var imgDisplaySize = "height:100px;max-width:130px";
                        var cls = "col-md-2 col-sm-4 col-xs-6";
                        var block;
                        
                        if('ontouchstart' in document.documentElement)
                           block = "<div id='"+v.file_id+"' class='"+cls+"' style='text-align:center'><img src='"+imgUrl+"' alt='"+v.label+"' style='"+imgDisplaySize+"' /><p>"+v.label+"</p></div>";
                        else
                           block = "<div id='"+v.file_id+"' class='"+cls+"' style='text-align:center'><a href='"+imgUrl+"'><img src='"+imgUrl+"' alt='"+v.label+"' style='"+imgDisplaySize+"' /></a><p>"+v.label+"</p></div>";

                        $("#gallery").append(block);
                        });
                    
                    if('ontouchstart' in document.documentElement){
                        touchstart = 'touchstart';
                        touchend = 'touchend'
                    }
                    $.each($US.file_id,(e,v)=>{
                        $("#"+v).off(touchstart);
                        $("#"+v).on(touchstart,$.proxy(()=>{
                            timer = setTimeout($US.deleteFile.bind(null,v), 800);
                        },null,e,v));
                        
                        $("#"+v).on(touchend,()=>{
                            clearTimeout(timer);
                        });
                    });
                }
                else
                box.html("    目前还没有上传图片。");
            },
            error: function (xhr, status, thrownError) { $US.showError('msg', xhr.responseText); }
        });
    },
    deleteFile: function(id){
        var res = confirm("真的要删除这张图片吗?");
        if(res) {
            var json = '{"api_key":"'+api_key+'","token":"'+token+'","id":"'+id+'"}';
            $.ajax({
                url: serviceLocation + "api/delete-file.php",
                type: "POST",
                data: json,
                contentType: 'application/json; charset=utf-8',
                success: function(data) {
                    if (typeof data == 'string') data = JSON.parse(data);
                    if(data.msg)
                        $US.showError('msg',data.msg);
                    else{
                        $("#gallery").html('');
                        $US.showImages();
                    }
                },
                error: function (xhr, status, thrownError) { $US.showError('msg', xhr.responseText); }
            });
        }
    }
};
Project: UService
Reference:

Handling long-press event

Passing parameters to event handler, setTimeout

PHP AJAX Multiple Image Upload using jQuery

Leave a Reply

Your email address will not be published. Required fields are marked *