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!

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

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.


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

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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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.

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),