jquery+HTML5+Ajax implements file upload function with progress bar
This time I will bring you jquery HTML5 Ajax to implement the file upload function with a progress bar. What are the precautions for jquery HTML5 Ajax to implement the file upload function with a progress bar. , the following is a practical case, let’s take a look.
First of all, HTML5 uses AJAX to submit data. First, you need to learn a newly added object in HTML5: FormDataThe FormData object can use the append method to add key-value data, which is different from the json we commonly used before. What is possible is that binary files can be uploaded asynchronously.1. Creation of FormDate object
var formData = new FormData();
2. Adding data to FormDate object
formData.append("catname", "我是一只喵"); formData.append("age", 1); // 数字类型会转为字符串类型 // 可以增加上传的二进制文件,比如fileInputElement对象中已经包含了用户所选择的文件 formData.append("userfile", fileInputElement.files[0]); //也可以将一个 Blob 对象添加到 formData 中 var oFileBody = "<a><b>hey!</b></a>"; var oBlob = new Blob([oFileBody], { type: "text/xml"}); formData.append("webmasterfile", oBlob);
3. Using the FormData object
var xhr = new XMLHttpRequest(); xhr.open("POST", "upload"); xhr.send(formData);
HTML part
After the brief introduction of the FormData object, let’s take a look at how the HTML code of the page is written
<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/5bc172cb195da0b52ebc2e3151b609aa-0.png?x-oss-process=image/resize,p_40" class="lazy" alt="jquery+HTML5+Ajax implements file upload function with progress bar" ><br> <input> <input><br> <p> </p><p></p>The p at the bottom is used to display the progress bar, so the corresponding css style is required. The style is as follows, the color is not good-looking, change it yourself:
<style> #parent{width:550px; height:10px; border:2px solid #09F;} #son {width:0; height:100%; background-color:#09F; text-align:center; line-height:10px; font-size:20px; font-weight:bold;} </style>
JS part
The highlight is here, after loading jquery on the page, let’s see how to write JavaScript First, the onchange event method of the file component:function showPic(){ var pic = $("#pic").get(0).files[0]; $("img").prop("src" , window.URL.createObjectURL(pic) ); }The first line of showPic is to get the uploaded file from the file object. The second line sets the src attribute for img. You can get an instant preview of the effect on the page. Before looking at the uploadFile method, let us briefly learn about the progress of progress events (Progress Events)... The Progress Events specification is a working draft of the W3C, defined Events related to client-server communication. These events were originally targeted at XHR operations, but are now also used by other APIs. There are the following 6 progress events. loadstart: Triggered when the first byte of corresponding data is received.
progress: Triggered continuously during the period of receiving the corresponding response. // Let’s just look at one
error: Triggered when an error occurs in the request.
abort: Triggered when the link is terminated due to calling the abort() method.
load: Triggered when complete corresponding data is received.
Loadend: Triggered after communication is completed or error, abort or load event is triggered.
Event processing program will receive an event object, whose target attribute is an XHR object, but contains three additional attributes:
lengthComputable: a Boolean value indicating whether progress information is available position: Indicates the number of bytes that have been received totalSize: Indicates the expected number of bytes determined based on the corresponding Content-Length header. With this information, we can create a progress indicator for the user. But the problem comes again, jQuery's ajax method has no operations on the progress event. How to play this~~ Fortunately, after consulting the information, I found that the XMLHttpRequest object called by jQuery's ajax method can be specified! ! !function uploadFile(){ // 获取上传文件,放到 formData对象里面 var pic = $("#myhead").get(0).files[0]; var formData = new FormData(); formData.append("file" , pic); $.ajax({ type: "POST", url: "upload", data: formData , //这里上传的数据使用了formData 对象 processData : false, //必须false才会自动加上正确的Content-Type contentType : false , //这里我们先拿到jQuery产生的 XMLHttpRequest对象,为其增加 progress 事件绑定,然后再返回交给ajax使用 xhr: function(){ var xhr = $.ajaxSettings.xhr(); if(onprogress && xhr.upload) { xhr.upload.addEventListener("progress" , onprogress, false); return xhr; } } }); }Finally add the onprogress method to bring the entire function to an end.
/** * 侦查附件上传情况 ,这个方法大概0.05-0.1秒执行一次 */ function onprogress(evt){ var loaded = evt.loaded; //已经上传大小情况 var tot = evt.total; //附件总大小 var per = Math.floor(100*loaded/tot); //已经上传的百分比 $("#son").html( per +"%" ); $("#son").css("width" , per +"%"); }Finally, the code of the entire page is attached for easy comparison.
nbsp;html> <title>html5_2.html</title> <meta> <style> #parent{width:550px; height:10px; border:2px solid #09F;} #son {width:0; height:100%; background-color:#09F; text-align:center; line-height:10px; font-size:20px; font-weight:bold;} </style> <script></script> <script> function showPic(){ var pic = $("#pic").get(0).files[0]; $("img").prop("src" , window.URL.createObjectURL(pic) ); uploadFile(); } function uploadFile(){ var pic = $("#pic").get(0).files[0]; var formData = new FormData(); formData.append("file" , pic); /** * 必须false才会避开jQuery对 formdata 的默认处理 * XMLHttpRequest会对 formdata 进行正确的处理 */ $.ajax({ type: "POST", url: "upload", data: formData , processData : false, //必须false才会自动加上正确的Content-Type contentType : false , xhr: function(){ var xhr = $.ajaxSettings.xhr(); if(onprogress && xhr.upload) { xhr.upload.addEventListener("progress" , onprogress, false); return xhr; } } }); } /** * 侦查附件上传情况 ,这个方法大概0.05-0.1秒执行一次 */ function onprogress(evt){ var loaded = evt.loaded; //已经上传大小情况 var tot = evt.total; //附件总大小 var per = Math.floor(100*loaded/tot); //已经上传的百分比 $("#son").html( per +"%" ); $("#son").css("width" , per +"%"); } </script> <img alt="jquery+HTML5+Ajax implements file upload function with progress bar" ><br> <input> <input><br> <p> </p><p></p>I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:
Jquery LigerUI detailed explanation of file upload steps
jquery dynamically loaded js file detailed explanation
How to read XML file content with jQuery
The above is the detailed content of jquery+HTML5+Ajax implements file upload function with progress bar. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

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.

Notepad++7.3.1
Easy-to-use and free code editor