文件上传速度
接口支持
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.osvue.win.app.common.ResultBean;
@RequestMapping("attachment")
@RestController
public class UploaderController {
@RequestMapping("upload")
public ResultBean upload(HttpServletRequest request) {
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
String tempPath = "/";
factory.setRepository(new File(tempPath));
factory.setSizeThreshold(1024 * 1024 * 10);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
upload.setFileSizeMax(1024 * 1024 * 50L);
upload.setSizeMax(1024 * 1024 * 50L);
List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
InputStream in = null;
for (FileItem fileItem : items) {
if (fileItem.isFormField()) {
String name = fileItem.getFieldName();
String value = fileItem.getString();
System.out.println(name +"---"+ value);
} else {
in = fileItem.getInputStream();
}
}
if (in != null) {
byte[] buffer = new byte[1024];
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len = 0;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
String str = out.toString();
Thread.sleep(5000);
System.out.println(str);
}
} catch ( Exception e) {
e.printStackTrace();
}
return ResultBean.ok().put("success", "hello00");
}
}
planA
<!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 = "/attachment/upload";
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" οnclick="UpladFile()" value="上传" />
<input type="button" οnclick="cancleUploadFile()" value="取消" />
</body>
</html>
planB
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#progress {
height: 10px;
width: 500px;
border: 1px solid gold;
position: relative;
border-radius: 5px;
}
#progress .progress-item {
height: 100%;
position: absolute;
left: 0;
top: 0;
background: chartreuse;
border-radius: 5px;
transition: width .3s linear;
}
</style>
</head>
<body>
文件上传框<br>
<input type="file" id="file"><br>
显示进度条<br>
<div id="progress">
<div class="progress-item"></div>
</div>
上传成功后的返回内容<br>
<span id="callback"></span>
<button onclick="upload()">上传文件</button>
</body>
<script>
document.querySelector("#file").addEventListener("change",
(e) => {
console.log(e)
}
);
function upload() {
var file = document.querySelector("#file").files[0];
var formdata = new FormData();
formdata.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open("post", "/attachment/upload");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.querySelector("#callback").innerText = xhr.responseText;
}
}
xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
var percent = event.loaded / event.total * 100;
document.querySelector("#progress .progress-item").style.width = percent + "%";
}
}
xhr.send(formdata);
}
</script>
</html>