123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>XMLHttpRequest上传文件</title>
- <script type="text/javascript">
-
- var xhr;
-
- function UpladFile() {
- var fileObj = document.getElementById("file").files[0];
- var url = "http://localhost:8080" + "/generalReportTemplate";
- var form = new FormData();
- form.append("file", fileObj);
- xhr = new XMLHttpRequest();
- xhr.open("post", url, true);
- xhr.onload = uploadComplete;
- xhr.onerror = uploadFailed;
- xhr.upload.onprogress = progressFunction;
- xhr.upload.onloadstart = function () {
- ot = new Date().getTime();
- oloaded = 0;
- };
- xhr.send(form);
- }
-
- function uploadComplete(evt) {
-
- var data = JSON.parse(evt.target.responseText);
- if (data.success) {
- alert("上传成功!");
- } else {
- alert("上传失败!");
- }
- }
-
- function uploadFailed(evt) {
- alert("上传失败!");
- }
-
- function cancleUploadFile() {
- xhr.abort();
- }
-
- function progressFunction(evt) {
- var progressBar = document.getElementById("progressBar");
- var percentageDiv = document.getElementById("percentage");
-
- if (evt.lengthComputable) {
- progressBar.max = evt.total;
- progressBar.value = evt.loaded;
- percentageDiv.innerHTML = Math.round(evt.loaded / evt.total * 100) + "%";
- }
- var time = document.getElementById("time");
- var nt = new Date().getTime();
- var pertime = (nt - ot) / 1000;
- ot = new Date().getTime();
- var perload = evt.loaded - oloaded;
- oloaded = evt.loaded;
-
- var speed = perload / pertime;
- var bspeed = speed;
- var units = 'b/s';
- if (speed / 1024 > 1) {
- speed = speed / 1024;
- units = 'k/s';
- }
- if (speed / 1024 > 1) {
- speed = speed / 1024;
- units = 'M/s';
- }
- speed = speed.toFixed(1);
-
- var resttime = ((evt.total - evt.loaded) / bspeed).toFixed(1);
- time.innerHTML = ',速度:' + speed + units + ',剩余时间:' + resttime + 's';
- if (bspeed == 0) time.innerHTML = '上传已取消';
- }
- </script>
- </head>
- <body>
- <progress id="progressBar" value="0" max="100" style="width: 300px;"></progress>
- <span id="percentage"></span><span id="time"></span>
- <br/><br/>
- <input type="file" id="file" name="myfile"/>
- <input type="button" onclick="UpladFile()" value="上传"/>
- <input type="button" onclick="cancleUploadFile()" value="取消"/>
- </body>
- </html>
|