1. 程式人生 > >原生JS實現ajax上傳檔案並顯示進度條

原生JS實現ajax上傳檔案並顯示進度條

html程式碼

<progress id="progressbar" value="0" max="100" style="width:300px;"></progress><span id="percentage"></span>
<input type="file" id="file" name="file" />
<input type="button" onclick="uploadFile()" value="上傳" />
<div id="fileimg">
    <div id="loading-cover"
></div> <div id="showloading"></div> </div>

css程式碼

#fileimg{
        width:300px;
        height: 300px;
        overflow: hidden;
        border:1px solid #ddd;
        position: relative;
    }
    #fileimg img {
        width: 100%;
        position: absolute;
        top:0
; left: 0; z-index: 1; }
#loading-cover{ width: 300px; height: 300px; position: absolute; background: rgba(0,0,0,0.3); top:0; left: 0; z-index: 2; } #showloading{ width: 300px; position: absolute; bottom
: 0
; text-align: center; z-index: 3; }

js程式碼

function uploadFile(){
    var fileObj = document.getElementById('file').files[0]; 
    showImg(fileObj);
    if(fileObj){
        var url = "uploadimage.jsp";
        var form = new FormData();
        form.append('myfile',fileObj);
        xhr = new XMLHttpRequest();
        xhr.open("post",url,true);
        xhr.onload = uploadComplete; //請求完成
        xhr.onerror =  uploadFailed; //請求失敗
        xhr.upload.onprogress = progressFunction;
        xhr.send(form);
    }else{
    alert('請選擇檔案');
    }
}

function showImg(fileObj){
    var fileimg = document.getElementById('fileimg');   
    var src = window.URL.createObjectURL(fileObj);
    var img = document.createElement("img");
     img.src = src;
     fileimg.appendChild(img);
}
function progressFunction(evt){
    var loadingCover = document.getElementById('loading-cover');
    var showloading = document.getElementById('showloading');
    var progressBar = document.getElementById('progressbar');
    var percentage = document.getElementById('percentage');
    if(evt.lengthComputable){
        progressbar.max = evt.total;
        progressBar.value = evt.loaded;
        var loading = Math.round(evt.loaded / evt.total * 100);
        percentage.innerHTML = loading + '%';
        showloading.innerHTML = loading + '%';
        loadingCover.style.top = -loading + '%';
        if(loading==100){
            showloading.style.display = 'none';
        }
    }
}
function uploadComplete(evt) {
  //服務斷接收完檔案返回的結果
  //    alert(evt.target.responseText);
      console.log("上傳成功!");
 }
 //上傳失敗
 function uploadFailed(evt) {
     console.log(evt);
 }