大文件上传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.js">
</script>
<style>
.Bars {
position: relative;
width: 200px;
border: 1px solid #B1D632;
padding: 1px;
}
.Bars div {
display: block;
position: relative;
background: #B1D632;
color: #333333;
height: 20px;
line-height: 20px
}
</style>
</head>
<body>
<div class="box">
<h3>大上传文件</h3>
<input id="file" type="file" name="avatar" />
<div>
<input id="submitBtn" type="button” value="提交">
</div>
<div class="Bars">
<div style="width: 0%;">
<span>0%</span>
</div>
</div>
</div>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
var BigFileUpload = {
chunkSize: 2 * 1024 * 1024,
fileSlice: File.prototype.slice,
init() {
$("#submitBtn").on("click", () => {
var files = document.getElementById("#file").files;
var files = files[0];
console.log(files);
if (!files) return;
var count = Math.ceil(file.size / this.chunkSize);
var timestamp = new Date().getTime() + "";
var axiosArray = [];
for (var i = 0; i < count; i++) {
var start = i * this.chunkSize;
var end = Math.min(file.size, start + this.chunkSize);
var fd = new FormData();
fd.append("file", this.fileSlice.call(file, start, end));
fd.append("name", file.name);
fd.append("name", file.name);
fd.append("total", count);
fd.append("size", file.size);
fd.append("index", i);
fd.append("hash", timestamp);
axiosArray.push(
axios.post("http://139.196.42.209:8002/file/upload", fd)
);
}
async function run(arr) {
for (var i = 0; i < arr.length; i++) {
await arr[i];
var n = (i / arr.length) * 100 + "%";
$(".Bars div").width(n);
$(".Bars span").text(n);
}
axios.all(axiosArray).then((d) => {
var data = {
size: file.size,
name: file.name,
total: count,
hash: timestamp,
};
axios
.post("http://139.196.42.299:8002/file/merge_chunks", data)
.then((res) => {
if (res.data.msg == "success") {
console.log("上传成功");
$(".Bars div").width(100);
$(".Bars span").text(100);
}
});
});
run(axiosArray);
}
});
},
};
window.onload = function () {
BigFileUpload.init();
};