web文件上傳,帶進度條

 

原生ajax上傳帶進度條 (百分比)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上傳 原生ajax上傳</title>
<style type="text/css">
.container{
    width: 200px;
    height: 20px;
    background-color: gray;
}
#progress{
    height: 20px;
    background-color: orange;
    display: inline-block;
}
    
</style>
</head>
<body>
    <form action="${pageContext.request.contextPath }/upload"
        enctype="multipart/form-data" method="post">
         上傳文件1: <input type="file" name="file1" id="file"><br /> 
         <div class='container'>
             <span id="progress"></span>
         </div>
    </form>
    <br>
    <button onclick="fileSelected()">文件信息</button><button onclick="uploadFile()">確認上傳</button>
    <div id="info">
        <div id="fileName"></div>
        <div id="fileSize"></div>
        <div id="fileType"></div>
    </div>
    <div id="result"></div>
    <script>
        function fileSelected() {
            var file = document.getElementById('file').files[0];
            if (file) {
                var fileSize = 0;
                if (file.size > 1024 * 1024)
                    fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
                else
                    fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
                document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
                document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
                document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
            }
        }
        function uploadFile() {
            var fd = new FormData();
            fd.append("file", document.getElementById('file').files[0]);
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener("progress", uploadProgress, false);
            xhr.addEventListener("load", uploadComplete, false);
            xhr.addEventListener("error", uploadFailed, false);
            xhr.addEventListener("abort", uploadCanceled, false);
            xhr.open("POST", "${pageContext.request.contextPath }/upload");//修改爲本身的接口
            xhr.send(fd);
        }

        function uploadProgress(evt) {
            if (evt.lengthComputable) {
                var percent = Math.round(evt.loaded * 100 / evt.total);
                
                document.getElementById('progress').innerHTML = percent.toFixed(2) + '%';
                document.getElementById('progress').style.width = percent.toFixed(2) + '%';
            }
            else {
                document.getElementById('progress').innerHTML = 'unable to compute';
            }
        }
        function uploadComplete(evt) {
            /* 服務器端返回響應時候觸發event事件*/
            document.getElementById('result').innerHTML = evt.target.responseText;
        }
        function uploadFailed(evt) {
            alert("There was an error attempting to upload the file.");
        }
        function uploadCanceled(evt) {
            alert("The upload has been canceled by the user or the browser dropped the connection.");
        }
    </script>
    
</body>
</html>

 

 

 

Jquery ajax上傳帶進度條 (bytes進度)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上傳 jquery上傳</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<style type="text/css">
.container{
    width: 200px;
    height: 20px;
    background-color: gray;
}
#progress{
    height: 20px;
    background-color: orange;
    display: inline-block;
}
    
</style>
</head>
<body>
    <form action="${pageContext.request.contextPath }/upload"
        enctype="multipart/form-data" method="post">
         上傳文件1: <input type="file" name="file1"><br /> 
         <div class='container'>
             <span id="progress"></span>
         </div>
    </form>
    <br>
    <button onclick="upload()">確認上傳</button>
    <div id="info"></div>
    <div id="result"></div>
    <script>  
        var totalSize = 0;  
          
        //綁定全部type=file的元素的onchange事件的處理函數  
        $(':file').change(function() {  
            var file = this.files[0]; //假設file標籤沒打開multiple屬性,那麼只取第一個文件就好了  
            name = file.name;  
            size = file.size;  
            type = file.type;  
            url = window.URL.createObjectURL(file); //獲取本地文件的url,若是是圖片文件,可用於預覽圖片  
              
            totalSize += size;  
            $("#info").html("文件名:" + name + "<br>文件類型:" + type + "<br>文件大小:" + size + "<br>url: " + url);  
              
        });  
      
        function upload() {  
            //建立FormData對象,初始化爲form表單中的數據。須要添加其餘數據可以使用formData.append("property", "value");  
            var formData = new FormData($('form')[0]);  
              
            //ajax異步上傳  
            $.ajax({  
                url: "${pageContext.request.contextPath }/upload",  
                type: "POST",  
                data: formData,  
                xhr: function(){ //獲取ajaxSettings中的xhr對象,爲它的upload屬性綁定progress事件的處理函數  
                  
                    myXhr = $.ajaxSettings.xhr();  
                    if(myXhr.upload){ //檢查upload屬性是否存在  
                        //綁定progress事件的回調函數  
                        myXhr.upload.addEventListener('progress',progressHandlingFunction, false);   
                    }  
                    return myXhr; //xhr對象返回給jQuery使用  
                },  
                success: function(result){  
                    $("#result").html(result);  
                },  
                contentType: false, //必須false纔會自動加上正確的Content-Type  
                processData: false  //必須false纔會避開jQuery對 formdata 的默認處理  
            });  
        }         
      
        //上傳進度回調函數:  
        function progressHandlingFunction(e) {  
            if (e.lengthComputable) {  
                $('#progress').attr({value : e.loaded, max : e.total}); //更新數據到進度條  
                var percent = e.loaded/e.total*100;  
                $('#progress').html(e.loaded + "/" + e.total+" bytes. " + percent.toFixed(2) + "%");  
                $('#progress').css('width', percent.toFixed(2) + "%");
            }  
        }  
    </script>
</body>
</html>

 

 

 

 

 

 

 

轉 : https://www.cnblogs.com/h--d/p/Web.htmljavascript

https://www.cnblogs.com/zhangyongl/p/8312881.htmlcss

相關文章
相關標籤/搜索