ajax+php file upload with progress bar

Theoretically, there are many such file / image upload plug-ins, but in the process of use, there will be various problems, such as compatibility problems, background problems ~ ~, etc., so since I can't use others' wheels well, I'll build one by myself.

In this paper, jq.ajax and php are used to realize the upload function. The front-end code is generally good. Some small partners are not php in the background. Please refer to the documents of your language for operation.

First look at the renderings. The whole upload interface is like this: View demo

  

Overall thinking:

1. Create input setting type=file, id=file, style setting opacity:0, position:absolute

2. Create a mask layer and set position:absolute and z-index greater than file

3. Create the FormData object and put the file into the FormData as the data

4. Create ajax, send FormData data to upload.php, listen to the progress event of ajax, and return the upload progress in real time

5. Output server's response on html page

6. After the upload is completed, click the "continue to upload" button to open the file selection box to continue to upload.

HTML part, relatively simple:

<div class="upload"> <div class="uploadBox">
    <span class="inputCover">Select file</span>
	<form enctype="">
	    <input type="file" name="file" id="file" />
	    <button type="button" class="submit">upload</button>
	</form>
	<button type="button" class="upagain">Continue uploading</button>
	<span class="processBar"></span>
	<span class="processNum">No file selected</span>
    </div>
</div>

CSS, style can be adjusted freely according to personal preferences, here is only for reference:

*{
    font-family: 'microsoft yahei';
    color: #4A4A4A;
}
.upload{
    width: 700px;
    padding: 20px;
    border: 1px dashed #ccc;
    margin: 100px auto;
    border-radius: 5px;
}
.uploadBox{
    width: 100%;
    height: 35px;
    position: relative;
}
.uploadBox input{
    width: 200px;
    height: 30px;
    background: red;
    position: absolute;
    top: 2px;
    left: 0;
    z-index: 201;
    opacity: 0;
    cursor: pointer;
}
.uploadBox .inputCover{
    width: 200px;
    height: 30px;
    position: absolute;
    top: 2px;
    left: 0;
    z-index: 200;
    text-align: center;
    line-height: 30px;
    font-size: 14px;
    border: 1px solid #009393;
    border-radius: 5px;
    cursor: pointer;
}
.uploadBox button.submit{
    width: 100px;
    height: 30px;
    position: absolute;
    left: 230px;
    top: 2px;
    border-radius: 5px;
    border: 1px solid #ccc;
    background: #F0F0F0;
    outline: none;
    cursor: pointer;
}
.uploadBox button.submit:hover{
    background: #E0E0E0;
}
.uploadBox button.upagain{
    width: 100px;
    height: 30px;
    position: absolute;
    left: 340px;
    top: 2px;
    display: none;
    border-radius: 5px;
    border: 1px solid #ccc;
    background: #F0F0F0;
    outline: none;
    cursor: pointer;
}
.uploadBox button.upagain:hover{
    background: #E0E0E0;
}
.processBar{
    display: inline-block;
    width: 0;
    height: 7px;
    position: absolute;
    left: 500px;
    top: 14px;
    background: #009393;
}
.processNum{
    position: absolute;
    left: 620px;
    color: #009393;
    font-size: 12px;
    line-height: 35px;
}

JS part, jq.ajax:

$(document).ready(function(){
    var inputCover = $(".inputCover");
    var processNum = $(".processNum");
    var processBar = $(".processBar");
    //Upload preparation information
    $("#file").change(function(){
        var file = document.getElementById('file');
        var fileName = file.files[0].name;
	var fileSize = file.files[0].size;
        processBar.css("width",0); 
        //Verify files to upload
	if(fileSize > 1024*2*1024){
	    inputCover.html("<font>The file is too large, please select again</font>");
	    processNum.html('No file selected');
	    document.getElementById('file').value = '';
	    return false;
	}else{
	    inputCover.html(fileName+' / '+parseInt(fileSize/1024)+'K');
	    processNum.html('Waiting for uploading');
	}
    })

    //Submit validation
    $(".submit").click(function(){
	if($("#file").val() == ''){
            alert('Please select file first!');
	}else{
	    upload();
	}
    })

    //Create ajax object and send upload request
    function upload(){
        var file = document.getElementById('file').files[0];
	var form = new FormData();
	form.append('myfile',file);
	$.ajax({
	    url: 'upload.php',//Upload address
	    async: true,//asynchronous
	    type: 'post',//post mode
	    data: form,//FormData data
	    processData: false,//Do not process data flow! important
 	    contentType: false,//Do not set http header! important
 	    xhr:function(){//Get upload progress            
                myXhr = $.ajaxSettings.xhr();
                if(myXhr.upload){
                    myXhr.upload.addEventListener('progress',function(e){//Listen for progress events
                    var loaded = e.loaded;//Uploaded
                        var total = e.total;//Total size
                        var percent = Math.floor(100*loaded/total);//Percentage
                        processNum.text(percent+"%");//Digital display progress
                        processBar.css("width",percent+"px");//Graphic progress}, false);
                }
                return myXhr;
            },
 	    success: function(data){//Upload successful callback
 		console.log("The current location of the document is:"+data);//Get file links
 		document.cookie = "url="+data;//This line can be ignored
 		$(".submit").text('Upload success');
 		$(".upagain").css("display","block");
             }
	})
    }

    //Continue uploading
    $(".upagain").click(function(){
	$("#file").click();
	processNum.html('No file selected');
        processBar.css("width",0); 
        $(".submit").text('upload');
	document.getElementById('file').value = '';
	$(this).css("display","none");
    })
})

After uploading, upload.php processes the file (for the sake of server security, only code fragments are posted):

<?php  
if(isset($_FILES["myfile"])){  
    move_uploaded_file($_FILES["myfile"]["tmp_name"],"ajax/".$_FILES["myfile"]["name"]);
    echo "http://www.xuxiangbo.com/ajax/".$_FILES["myfile"]["name"];
}else{
    echo 'no file';
}
?> 

Original address: http://blog.xuxiangbo.com/im-22.html

Tags: PHP

Posted on Sat, 04 Apr 2020 22:42:20 -0700 by VBAssassin