利用XMLHttpRequest实现页面无刷新上传文件

废话不多说,直接贴代码

    

     function fileSelected(userfile) {
        uploadFile(userfile);
    }
    function uploadFile(userfile) {
        var fd = new FormData();
        fd.append("userfile",userfile.files[0]);//文件追到到FormData
        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", "文件上传地址");
        xhr.send(fd);
    }

    //图片上传进度
    function uploadProgress(evt) {
        if (evt.lengthComputable) {
            var percentComplete = Math.round(evt.loaded * 100 / evt.total);
            console.log(percentComplete)
        }else {
        }
    }
    
    //图片上传完成
    function uploadComplete(evt) {
        var json = eval('(' + evt.target.responseText + ')');
       //图片上传完成服务器相应
        console.log(json)
    }

    function uploadFailed(evt) {
        alert("上传失败");
    }

    function uploadCanceled(evt) {
        // alert("已经取消上传");
    }

你可能感兴趣的:(利用XMLHttpRequest实现页面无刷新上传文件)