Home Web Front-end JS Tutorial Node.js implements file upload progress bar compatible with IE789

Node.js implements file upload progress bar compatible with IE789

Dec 24, 2016 pm 05:21 PM

Nodejs processing of file uploads

In Express4, req.files is already undefined; the most commonly used one now may be formidable. You know that it has a progress event, so you are very happy. The progress bar of lower versions of IE works well. OK, try it:

form
.on('error',function(err){
 console.log(err);
})
.on('aborted',function(){
 console.log('aborted');
})
.on('progress',function(bytesReceived, bytesExpected){
 var n=parseInt(parseFloat(bytesReceived/bytesExpected).toFixed(2)*100);
 console.log(n);
});
Copy after login

Yes, you are happy to see that the console printed a series of progress values ​​as expected; then, go one step further;

form
.on('progress',function(bytesReceived, bytesExpected){
 var n=parseInt(parseFloat(bytesReceived/bytesExpected).toFixed(2)*100);
 res.write(&#39;<script>window.parent.call(&#39;+n+&#39;)</script>&#39;);
 //无刷新上传,你们懂的 console.log(n);
});
Copy after login

call method is Display the progress value on the page; unfortunately, you can only see the last 100% and cannot see the specific and detailed progress value of the upload; explore again...

Next, change your mind, try it, and save the progress value to In the session, add an additional request to poll this progress value. Oops, not bad! In order to ensure that the progress value of your request is the progress value of your current upload and not the progress value of other uploads, you need to agree on a token value in the upload request and additional requests; now another question arises: how to specify the value when requesting After getting this token, since the request body of the file upload is in the Request Payload, req.body cannot get the passed value. I don’t want to parse this pile. Of course, I can’t parse it. It’s best to put it in the URL. The problem The problem is that sometimes you have to refresh the token twice, which is not good! As a last resort, I'd better put it in a cookie!

var cookies=function () {
 var cks=req.headers.cookie.split(&#39;;&#39;),obj={};
 for(var i=0;i<cks.length;i++){
  obj[cks[i].split(&#39;=&#39;)[0].replace(/\s+/ig,&#39;&#39;)]=unescape(cks[i].split(&#39;=&#39;)[1]);
 }
 return obj;
}();
var queryToken=cookies.__token__;
 
form .on(&#39;progress&#39;,function(bytesReceived, bytesExpected){
 var n=parseInt(parseFloat(form.bytesReceived/form.bytesExpected).toFixed(2)*100);
 if (req.session[&#39;file&#39;+queryToken]) { 
  req.session[&#39;file&#39;+queryToken].percent=n;
 }else{
  req.session[&#39;file&#39;+queryToken]={
   token:queryToken,
   percent:n
  }
 };
 console.log(n);
});
Copy after login

For IE789, I came to poll the progress value. Forgive me, my heart actually hurts;

var getData=function(){
 $.post(&#39;/uploader&#39;,{
  getfileinfo:1,
  uploadtoken:utils.cookie.getCookie(&#39;__token__&#39;)
 })
 .then(function(data){
  console.log(data);
  if (data.mes<0) {
   getData();
  }else{
   var pros=data.info;
   call(pros.percent);
   if (pros.percent!=&#39;100&#39;) {
    getData();
   };
  };
 });
}
getData();
Copy after login

The call method displays the progress value on the page; unfortunately, you only I can see the last 100%, but I can't see the specific and detailed progress value of the upload; explore again...

Okay, I've fallen into trouble again; but I still feel something is wrong. There is no problem with ajax polling, but the problem lies in the session. The value will not be available until the upload is completed, so you can only see 100% and not the detailed progress value; can I think that in progress, the previous res.write and this time's req.session are suspended, but It also saves the results of each execution until the progress is completed and then releases it, so you can only see 100%; I am not in the mood to look at the source code of formidable, and of course I can’t understand it, so I’ll just think so for now!

Since there is no problem with ajax polling, then saving it to the session is not working. If it doesn’t work, try putting it in the global object. It will not hang if you put a value in the global object. Make some changes and put it in the global object. In global:

form
.on(&#39;progress&#39;,function(bytesReceived, bytesExpected){
 var n=parseInt(parseFloat(form.bytesReceived/form.bytesExpected).toFixed(2)*100);
 if (global[&#39;file&#39;+queryToken]) {
  global[&#39;file&#39;+queryToken].percent=n;
 }else{
  global[&#39;file&#39;+queryToken]={
   token:queryToken,
   percent:n
  }
 };
 console.log(n);
});
Copy after login

Continue polling.

Beautiful, exactly like that! What you see in Chrome is the same as the progress of HTML5, except that it will feel a little stuck in IE789, but you can still see the detailed progress value; after all, the old browser is not very good, you know; also Yes, values ​​are added to the global every time it is uploaded. You have to clean it up properly. After the file is uploaded and transferred to the specified directory, global['file'+queryToken]=null;

However, polling is just a There may be problems here after receiving many requests; why not limit it and request the progress value every 500ms? Well, the IE789 progress bar is solved like this, and the flash is discarded as promised; although this polling is compatible with all browsers server, but after all, so many requests are wasted, so it is better to make a judgment and continue HTML5 outside of IE789!

In fact, if you weigh it, which one is more worth adding an extra flash upload or an extra request? Forgive me that I don’t know flash, so I won’t say more. Anyway, I don’t like adding extra files to the page;

Summary

Regarding the file upload component, there are still many details to deal with. I originally wanted to make a JS file, but then I thought, in order to be more reusable, it is better to make it as an independent page. Where it needs to be uploaded, Just iframe it, which is definitely much better than creating a JS file. The above is the entire content of this article. I hope it can be of some help to everyone's study or work. If you have any questions, you can leave a message to communicate.


For more related articles about Node.js implementing IE789-compatible file upload progress bar, please pay attention to the PHP Chinese website!


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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles