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
The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

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

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

The Role of HTML: Structuring Web ContentThe Role of HTML: Structuring Web ContentApr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTML and Code: A Closer Look at the TerminologyHTML and Code: A Closer Look at the TerminologyApr 10, 2025 am 09:28 AM

HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft