search
HomeWeb Front-endHTML TutorialHTML5关于上传API的一些使用(中)_html/css_WEB-ITnose

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

关于上传事件

首先要做到实时进度条这种需求,首先我们需要得到关于上传的各种事件,这些事件大部分都是在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);

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

  • 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';    }}

上面这个方法是直接在某个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);}    

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

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

Statement
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
Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?Mar 04, 2025 pm 12:32 PM

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

How do I use HTML5 form validation attributes to validate user input?How do I use HTML5 form validation attributes to validate user input?Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

How to efficiently add stroke effects to PNG images on web pages?How to efficiently add stroke effects to PNG images on web pages?Mar 04, 2025 pm 02:39 PM

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

What are the best practices for cross-browser compatibility in HTML5?What are the best practices for cross-browser compatibility in HTML5?Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

What is the purpose of the <datalist> element?What is the purpose of the <datalist> element?Mar 21, 2025 pm 12:33 PM

The article discusses the HTML <datalist> element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <meter> element?What is the purpose of the <meter> element?Mar 21, 2025 pm 12:35 PM

The article discusses the HTML <meter> element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates <meter> from <progress> and ex

How do I use the HTML5 <time> element to represent dates and times semantically?How do I use the HTML5 <time> element to represent dates and times semantically?Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 <time> element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

What is the purpose of the <progress> element?What is the purpose of the <progress> element?Mar 21, 2025 pm 12:34 PM

The article discusses the HTML <progress> element, its purpose, styling, and differences from the <meter> element. The main focus is on using <progress> for task completion and <meter> for stati

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)