Node.js implements file upload progress bar compatible with IE789
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); });
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('<script>window.parent.call('+n+')</script>'); //无刷新上传,你们懂的 console.log(n); });
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(';'),obj={}; for(var i=0;i<cks.length;i++){ obj[cks[i].split('=')[0].replace(/\s+/ig,'')]=unescape(cks[i].split('=')[1]); } return obj; }(); var queryToken=cookies.__token__; form .on('progress',function(bytesReceived, bytesExpected){ var n=parseInt(parseFloat(form.bytesReceived/form.bytesExpected).toFixed(2)*100); if (req.session['file'+queryToken]) { req.session['file'+queryToken].percent=n; }else{ req.session['file'+queryToken]={ token:queryToken, percent:n } }; console.log(n); });
For IE789, I came to poll the progress value. Forgive me, my heart actually hurts;
var getData=function(){ $.post('/uploader',{ getfileinfo:1, uploadtoken:utils.cookie.getCookie('__token__') }) .then(function(data){ console.log(data); if (data.mes<0) { getData(); }else{ var pros=data.info; call(pros.percent); if (pros.percent!='100') { getData(); }; }; }); } getData();
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('progress',function(bytesReceived, bytesExpected){ var n=parseInt(parseFloat(form.bytesReceived/form.bytesExpected).toFixed(2)*100); if (global['file'+queryToken]) { global['file'+queryToken].percent=n; }else{ global['file'+queryToken]={ token:queryToken, percent:n } }; console.log(n); });
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!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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...

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 in JavaScript? When processing data, we often encounter the need to have the same ID...

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.

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. �...

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

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/)...

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.
