ajax异步文件上传和进度条
    		       		warning:
    		            这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
    		        
        		                
                使用Ajax进行文件上传时,可以结合FormData对象和XMLHttpRequest来实现异步上传文件,并且可以通过监听上传过程的事件来实现进度条的功能。以下是一个简单的实现示例:
HTML部分:
<form id="uploadForm">
    <input type="file" id="fileInput" name="file"/>
    <button type="button" id="uploadBtn">上传</button>
</form>
<div id="progressBar" style="width: 100%; background: #ddd;">
    <div id="progress" style="width: 0; background: #76D7C4; text-align: center; color: white;">0%</div>
</div>JavaScript部分:
document.getElementById('uploadBtn').onclick = function() {
    var fileInput = document.getElementById('fileInput');
    var file = fileInput.files[0];
    var xhr = new XMLHttpRequest();
 
    // 监听上传过程
    xhr.upload.onprogress = function(event) {
        if (event.lengthComputable) {
            var percentComplete = (event.loaded / event.total) * 100;
            var progressBar = document.getElementById('progress');
            var progressBarWidth = Math.round(percentComplete / 100 * progressBar.parentNode.offsetWidth);
            progressBar.style.width = progressBarWidth + 'px';
            progressBar.innerHTML = Math.round(percentComplete) + '%';
        }
    };
 
    // 上传完成
    xhr.onload = function() {
        if (xhr.status === 200) {
            console.log('上传成功');
        } else {
            console.log('上传失败');
        }
    };
 
    // 创建FormData对象并附加文件
    var formData = new FormData();
    formData.append('file', file);
 
    // 开始上传
    xhr.open('POST', '/upload', true);
    xhr.send(formData);
};这段代码中,我们定义了一个上传按钮的点击事件处理函数,在该函数中创建了XMLHttpRequest对象,并为它添加了上传过程的进度监听器。当用户点击上传按钮时,文件会被异步上传到服务器,同时进度条会实时更新显示上传进度。
注意:
- '/upload' 是服务器端接收上传文件的URL地址,需要根据实际情况进行替换。
- 服务器端需要能够处理文件上传,并且返回适当的响应。
- 进度条的样式可以根据需要进行自定义,这里使用了简单的CSS来模拟进度条的效果。
评论已关闭