• 0
  • 0

上传文件带进度条

2019-09-03 90 0 admin 所属分类:HTML

原生JS上传带进度条

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", "/upload.html");
    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.");
}

创建XMLHttp对象监听是个事件

Jquey ajax上传

var totalSize = 0;
//绑定id=file的元素的onchange事件的处理函数  
$('#file').change(function() {
    //假设file标签没打开multiple属性,那么只取第一个文件就行了 
    var file = this.files[0];  
    name = file.name;
    size = file.size;
    type = file.type;
    //获取本地文件的url,如果是图片文件,可用于预览图片  
    url = window.URL.createObjectURL(file); 
    totalSize += size;
    $("#info").html("文件名:" + name + "
文件类型:" + type + "
文件大小:" + size + "
url: " + url);
});

function upload() {
    //创建FormData对象,初始化为form表单中的数据。需要添加其他数据可使用formData.append("property", "value");  
    var formData = new FormData($('form')[0]);
    //ajax异步上传  
    $.ajax({
        url: "/upload.html",
        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) + "%");
    }
}


返回顶部