原生ajax 上传进度和下载进度

635 阅读1分钟

注意:

1. 上传进度使用xhr.upload.onprogress事件.
2. 下载进度使用xhr.onprogress事件.

上传 进度

<form>
	<input type="file" name="avatar">
	<button>上传</button>
</form>

<!-- 设置一个进度条,这里使用h5新标签,开始隐藏 -->
<progress max="0" value="0" style="display: none"></progress>


<script>
    document.querySelector('form').onsubmit = function (e) {
        e.preventDefault();
        // 使用FormData收集输入框的值(这里是选择的图片)
        var fd = new FormData(this);

        // ajax提交fd对象
        // 接口文档,查看ppt即可
        var xhr = new XMLHttpRequest();
        
        /*************************************************/
        /*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/
        // 找到 进度条标签 
        var progress = document.querySelector('progress');
        // 注册上传监听事件
        xhr.upload.onprogress = function (e) {
            progress.style.display = 'block';
            progress.max = e.total; // 文件总大小,单位字节
            progress.value = e.loaded; // 已经上传了多少字节
        }
        /*↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑*/
        /************************************************/
        
        xhr.onload = function () {
            console.log(this.responseText);
        }
        xhr.open('POST', 'http://www.itcbc.com:3006/api/formdata');
        xhr.send(fd);

    }
</script>

下载进度

xhr.onprogress = function (e) { 
    progress.style.display = 'block';
    progress.max = e.total; // 文件总大小,单位字节 progress.value = e.loaded; // 已经上传了多少字节
}