This article shares three Java asynchronous uploading methods for your reference. The specific content is as follows
The first method to upload using a browser plug-in requires a certain underlying coding skill. I won’t talk about it here, so as not to mislead people’s children. If you put this into consideration, you can Baidu on your own.
The second type uses a hidden iframe to simulate asynchronous uploads . Why is we talking about simulation here? Because we actually put the return result in a hidden iframe, so we did not make the current page jump, which felt like an asynchronous operation.
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Hidden iframe upload file</title><script type="text/javascript" src="jquery path..."></script></head><body><iframe name="frm" style="display:none"></iframe><form action="/upload2" enctype="multipart/form-data" method="post" target="frm" onsubmit="loading(true);"> <p id="upfile">Attachment: <input type="file" name="myfile" style="display: inline"> </p> <p id="upbtn"> <input style="padding-left:50px;padding-right: 50px;" type="submit" value="asynchronous upload"> <span id="uptxt" style="display: none">Uploading...</span> </p></form><div id="flist" style="border:1px dotted darkgray;"></div><script> // Callback function uploadFinished(fileName) { addToFlist(fileName); loading(false); } function addToFlist(fname) { var temp = ["<p id='" + fname + "'>", fname, "<button onclick='delFile(/"" + fname + "/");'>Delete</button>", "</p>" ]; $("#flist").append(temp.join(""));} function loading(showloading) { if (showloading) { $("#uptxt").show(); } else { $("#uptxt").hide; } } </script></body></html> There are two key points in this technology:
1.form will specify the target, and the submitted result will be returned to the hidden iframe. (i.e. the form target is consistent with the iframe's name attribute).
2. After the submission is completed, the page in the iframe communicates with the main page. How to notify the upload result and server file information communicate with the main page?
After receiving the file, we use nodejs to return a method defined by the window.parent. main page. After executing, we can know that the file upload is completed. The code is very simple:
router.post('/upload2', multipartMiddleware, function(req, res) { var fpath = req.files.myfile.path; var fname = fpath.substr(fpath.lastIndexOf('//') + 1); setTimeout(function { var ret = ["<script>", "window.parent.uploadFinished('" + fname + "');", "</script>"]; res.send(ret.join("")); }, 3000); }); After execution, you can open the developer option and you will find that some data returned from the hidden iframe is returned.
The third type uses XMLHttpRequest2 for real asynchronous uploads .
Or post the code first:
After execution, you can open the developer option and you will find that some data returned from the hidden iframe is returned. The third type uses XMLHttpRequest2 for real asynchronous uploads. Let's post the code first:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>xhr level2 asynchronous upload</title> <script type="text/javascript" src="jquery path..."></script> </head> <body> <div> <p id="upfile">Attachment: <input type="file" id="myfile" style="display: inline"></p> <p id="upbtn"> <input style="padding-left:50px;padding-right:50px;" type="button" value="asynchronous upload" onclick="upload;"> <span id="uptxt" style="display: none">Uploading...</span> <span id="upprog"></span> <button id="stopbtn" style="display:none;">Stop upload</button> </p> </div> <div id="flist" style="border:1px dotted darkgray;"></div> <script> function upload { // 1. Prepare FormData var fd = new FormData; fd.append("myfile", $("#myfile")[0].files[0]); // Create xhr object var xhr = new XMLHttpRequest; // Listen to the status and respond in real time // xhr and xhr.upload have progress events, xhr.progress is the download progress, xhr.upload.progress is the upload progress xhr.upload.onprogress = function(event) { if (event.lengthComputable) { var percent = Math.round(event.loaded * 100 / event.total); console.log('%d%', percent); $("#upprog").text(percent); } }; // Transmission start event xhr.onloadstart = function(event) { console.log('load start'); $("#upprog").text('Start upload'); $("#stopbtn").one('click', function { xhr.abort; $(this).hide();}); loading(true); }; // The ajax process successfully completed the event xhr.onload = function(event) { console.log('load success'); $("#upprog").text('upload success'); console.log(xhr.responseText); var ret = JSON.parse(xhr.responseText); addToFlist(ret.fname); }; // An error event occurred in ajax process xhr.onerror = function(event) { console.log('error'); $("#upprog").text('Error occurred'); }; // ajax is cancelled xhr.onabort = function(event) { console.log('abort'); $("#upprog").text('operation was cancelled'); }; // The loadend transmission ends, and it will be triggered regardless of success or failure xhr.onloadend = function (event) { console.log('load end'); loading(false); }; // initiate an ajax request to transmit data xhr.open('POST', '/upload3', true); xhr.send(fd); } function addToFlist(fname) { var temp = ["<p id='" + fname + "'>", fname, "<button onclick='delFile(/"" + fname + "/");'>Delete</button>", "</p>" ]; $("#flist").append(temp.join("")); } function delFile(fname) { console.log('to delete file: ' + fname); // TODO: Please implement} function loading(showloading) { if (showloading) { $("#uptxt").show(); $("#stopbtn").show(); } else { $("#uptxt").hide(); $("#stopbtn").hide(); } } </script> </body> </html> There is a lot of code, but it is easy to understand. Anyone who has used AJAX knows that XHR objects provide an onreadystatechange callback method to listen for the entire request/response process. There are several more progress events in the XMLHttpRequest level 2 specification. There are 6 events below:
1.loadstart: Triggered when the first byte of the response data is received.
2.progress: It is triggered continuously during the reception of the response.
3.error: Triggered when an error occurs in the request.
4.abort: Triggered when the connection is terminated because of calling the abort method.
5.load: Triggered when full response data is received.
6.loadend: Triggered after the communication is completed or the error, abort, load events are triggered.
This time we can interpret the code: when the transmission event starts, we add a click event on the stop transmission button, and the built-in abort method can stop transmission. If you do not click, it will be uploaded normally until the transmission is completed. Its background code is similar to the second method.
The three methods have their own advantages and disadvantages, let’s make a simple summary.
Third-party controls have good interactivity and controllability, because they are close to the bottom layer and their performance is also excellent. However, because it is difficult to write, you usually need to install plug-ins yourself, and sometimes you may need to write them yourself.
I personally think the hidden iframe method is a very thoughtful method. Iframe can help us do a lot of things. This approach has extensive browser compatibility and does not require plugins to be installed. However, it has poor interactivity, uncontrollable upload process, and its performance is also very average.
For XHR2 level pure ajax upload, it must have a higher version browser (ie9+). But it has very good interactiveness, you can see the upload progress and is controllable.
Development can be done differently according to requirements. I personally think that uploading these files, especially the second one, provides a kind of idea, which fully utilizes the characteristics of certain html tags, may be something that our developers need to think more.
The above is all about this article, I hope it will be helpful to everyone's learning.