Table of Contents
关于上传事件
关于实时进度条
关于实时上传速度的显示
Home Web Front-end HTML Tutorial HTML5关于上传API的一些使用(中)_html/css_WEB-ITnose

HTML5关于上传API的一些使用(中)_html/css_WEB-ITnose

Jun 24, 2016 am 11:28 AM

    上一次写了关于HTML的上传API,XMLHttpRequest2.0的上传方式,以及HTML5中上传之前本地的预览,包括对于图片以及部分信息的预览。这次我们就讲下HTML5中关于上传的一些各种个性化需求的处理,主要包括实时进度条,上传速度的实时显示等。
Copy after login

关于上传事件

首先要做到实时进度条这种需求,首先我们需要得到关于上传的各种事件,这些事件大部分都是在XMLHttpRequest这个对象下面:

  • progress事件:上传进度事件。
  • load事件:传输成功完成。
  • abort事件:传输被用户取消。
  • error事件:传输中出现错误。
  • loadstart事件:传输开始。
  • loadEnd事件:传输结束,但是不知道成功还是失败。

其中progress事件分为上传和下载两种情况,上传的时候progress事件实际上是在XMLHttpRequest.upload对象下面,而下载的时候属于XMLHttpRequest对象

关于实时进度条

我们可以在上篇中的方法基础上进行扩展来写实时进度条的方法,

var xhr=new XMLHttpRequest();  var formData=new FormData();  formData.append('name',"Jack");  formData.append('uid',666666);  xhr.open("post",url);  xhr.send(formData);  //上传中xhr.upload.addEventListener("progress", uploadProgress, false);//上传成功xhr.addEventListener("load", uploadComplete, false);//上传出错xhr.addEventListener("error", uploadFailed, false);//上传取消xhr.addEventListener("abort", uploadCanceled, false);
Copy after login

而上传事件还给我们提供了下面这些数据

  • total – 文件大小
  • loaded – 已上传的大小
  • lengthComputable – 进度是否可计算

通过上面这些事件以及属性就可以很轻易的写出进度条。

function uploadProgress(evt){   //evt 上传事件中返回的数据    if (evt.lengthComputable) { //判断进度是否可以计算        var percentComplete = Math.round(evt.loaded * 100 / evt.total); //对进度进行计算并且格式化        document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';     //输出100%    }else {        document.getElementById('progressNumber').innerHTML = 'unable to compute';    }}
Copy after login

上面这个方法是直接在某个div中直接显示百分比的数字,假如我们需要做进度条也很简单,可以添加一个标签,默认宽度为0,然后在uploadProgress方法中动态更改标签的宽度,单位为百分比,而值就是percentComplete,这样可以在上传的过程当中得到一个完整的进度条。

而当我们文件上传完毕之后可以在load事件中绑定的uploadComplete方法中去做一些css等UI的修改。

关于实时上传速度的显示

现在进度条有了,可是我们还想知道速度是多少应该怎么办呢。

可以通过计算的方法获取其上传的速度,我们在progress事件中是知道已上传的文件大小的,那我们在uploadProgress方法中没过1秒都去计算一下这一次和上一次的loaded大小就可以知道其每秒的上传速度。从而在页面上实时的更新当前的上传速度了。

代码如下

// currentLoadedBytesb本次上传的数据总量,// lastLoadedBytes 上一次上传的数据总量// oldObjUploadBits旧的上传速度var currentLoadedBytes,lastLoadedBytes,oldObjUploadBits;timer = setInterval(    function () {        var bytesCount = currentLoadedBytes - lastLoadedBytes;        if (bytesCount !== 0) {            var speed = ConvertBytesUnit(bytesCount);            $(obj).html("上传速度:" + speed.number + speed.unit + "/s");        } else {            $(obj).html(oldObjUploadBits);        }        oldObjUploadBits = $(obj).html();        lastLoadedBytes = currentLoadedBytes;    }, 1000)   function ConvertBytesUnit(size){    if (size < 0) size = 0;    var result = {};    if (size > 1024 * 1024) {        result.number = (size / (1024 * 1024)).toFixed(2);        result.unit = "MB";    } else if (size > 1024 ) {        result.number = (size / 1024).toFixed(2);        result.unit = "KB";    } else {        result.number = size.toFixed(2);        result.unit = "B";    }    return (result);}    
Copy after login

通过上面的方法就可以获得每一秒具体的上传速度了。

另外XMLHttpRequest2.0可以实现的功能其实很多,另外还可以实现断点续传,以及分片上传等更高级的功能。我们留在下一篇再来说。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Apr 04, 2025 pm 11:54 PM

GiteePages static website deployment failed: 404 error troubleshooting and resolution when using Gitee...

How to implement adaptive layout of Y-axis position in web annotation? How to implement adaptive layout of Y-axis position in web annotation? Apr 04, 2025 pm 11:30 PM

The Y-axis position adaptive algorithm for web annotation function This article will explore how to implement annotation functions similar to Word documents, especially how to deal with the interval between annotations...

HTML, CSS, and JavaScript: Essential Tools for Web Developers HTML, CSS, and JavaScript: Essential Tools for Web Developers Apr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? Apr 05, 2025 am 06:15 AM

To achieve the effect of scattering and enlarging the surrounding images after clicking on the image, many web designs need to achieve an interactive effect: click on a certain image to make the surrounding...

See all articles