zoukankan      html  css  js  c++  java
  • 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.html

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

  • 相关阅读:
    linux centos7环境下安装apache2.4+php5.6+mysql5.6 安装及踩坑集锦(二)
    linux centos7环境下安装apache2.4+php5.6+mysql5.6 安装及踩坑集锦
    C# 获取当前登录IP
    清除ios系统alert弹出框的域名
    在线文档预览示例
    lnmp1.5一键安装包安装lnmpa后,添加站点
    解决sql server2008数据库安装之后,web程序80端口被占用问题(终极方案)
    码云上传项目流程
    SQLServer2008不允许保存更改错误解决办法
    tp5 使用phpword 替换word模板并利用com组件转换pdf
  • 原文地址:https://www.cnblogs.com/fps2tao/p/11561521.html
Copyright © 2011-2022 走看看