效果图
效果图
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,viewport-fit=cover">
<title>文件上传</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div style="margin: 20px;">
<div id="fileDiv" style="display: none"></div>
<div>
<button type="button" id="selectFileBtn">选择文件</button>
<button type="button" id="uploadActionBtn">开始上传</button>
<div style="max-width: 1000px;">
<table border="1">
<colgroup>
<col width="150">
<col width="100">
<col width="260">
<col width="150">
</colgroup>
<thead>
<tr>
<th>文件名</th>
<th>大小</th>
<th>上传进度</th>
<th>操作</th>
</tr>
</thead>
<tbody id="demoList">
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
//模拟已有数据
function initDataList() {
for (let i = 0; i < 3; i++) {
var file = {};
file.id = i;
file.name = "文件名" + i;
file.size = (i + 1) * 100 * 1014;
var tr = $(['<tr id="upload-done' + file.id + '" data-fileid="' + file.id + '" >'
, '<td>' + file.name + '</td>'
, '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
, '<td><span>已上传 </span></td>'
, '<td>'
, '<button name="fileDelete" >删除</button>'
, '</td>'
, '</tr>'].join(''));
$("#demoList").append(tr);
}
$('button[name="fileDelete"]').off('click').on('click', function (e) {
var tr = $(this).parent().parent("tr");
tr.remove();
var val = $(tr).attr("id");
val = (val + "").split("-")[1];//
$("#uploaderInput-" + val).remove();
});
}
initDataList();
var fileTotalCount = 0;//用于记录文件
//选择文件
$("#selectFileBtn").on("click", function (e1) {
//没有选择文件的情况
if ($("#uploaderInput").length > 0) {
$("#uploaderInput").click();
} else {
var uploadFile = '<input name="files" id="uploaderInput" type="file" accept="image/png, image/jpeg, image/gif" />';
$("#fileDiv").append($(uploadFile));
$("#uploaderInput").off('change').on('change', function (e) {
var files = e.target.files;
var fileNum = files.length;
if (fileNum > 0) {
preview(files);
//修改id,加上编号
$(this).attr("id", "uploaderInput-" + fileTotalCount);
}
});
$("#uploaderInput").click();
}
});
//上传文件按钮
$("#uploadActionBtn").on("click", function (e) {
var filesInputs = $("input[name='files']");
for (let i = 0; i < filesInputs.length; i++) {
let fileInput = filesInputs[i];
let fileid = $(fileInput).data("fileid");
if (fileid) { //有文件id表示已上传,不重复传
continue;
}
let index = ($(fileInput).attr("id") + "-").split("-")[1];
var length = fileInput.files.length;
for (let j = 0; j < length; j++) {
var file = fileInput.files[j];
uploadFile(file, {
before: function () {
console.log("before");
},
done: function (res) {
if (res.code == 0) {
$(fileInput).attr("data-fileid", res.data.id);
$("tr#upload-" + index).attr("data-fileid", res.data.id);
}
},
progress: function (n) {
$("#progress-demo-"+index).text(n+"%")
// console.log("progress === "+n);
},
error: function (err) {
console.log("error === " + n);
},
});
}
}
});
//上传单个文件
function uploadFile(file, callback) {
if (callback) callback.before();
var progressRate = 0;
var t =setInterval(function () {
if (callback) callback.progress(++progressRate);
if(progressRate>=100){
clearInterval(t);
var res = {};
res.code = 0;
res.data = {
id: uuid(5, 16)//文件id
};
if (callback) callback.done(res);
}
},100);
// var formData = new FormData();
// formData.append("files", file);
// $.ajax({
// url: 'https://httpbin.org/post',
// type: 'POST',
// cache: false,
// processData: false,
// contentType: false,
// data: formData,
// xhr: function () {
// var xhr = new XMLHttpRequest();
// //使用XMLHttpRequest.upload监听上传过程,注册progress事件,打印回调函数中的event事件
// xhr.upload.addEventListener('progress', function (e) {
// //loaded代表上传了多少
// //total代表总数为多少
// var progressRate = (e.loaded / e.total) * 100;
//
// //通过设置进度条的宽度达到效果
// if (callback) callback.progress(progressRate);
// });
//
// return xhr;
// },
// success: function (res) {
//
// if (callback) callback.done(res);
// },
// error: function (err) {
// if (callback) callback.error(err);
// }
// });
}
function preview(files) {
var fileNum = files.length;
if (fileNum > 0) {
for (let i = 0; i < fileNum; i++) {
let file = files[i];
let fileName = file.name;
fileTotalCount++;
var tr = $(['<tr id="upload-' + fileTotalCount + '" >'
, '<td>' + file.name + '</td>'
, '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
, '<td><span id="progress-demo-' + fileTotalCount + '"> </span></td>'
, '<td>'
, '<button name="fileDelete" >删除</button>'
, '</td>'
, '</tr>'].join(''));
$("#demoList").append(tr);
}
$('button[name="fileDelete"]').off('click').on('click', function (e) {
var tr = $(this).parent().parent("tr");
tr.remove();
var val = $(tr).attr("id");
val = (val + "").split("-")[1];//
$("#uploaderInput-" + val).remove();
});
} else {
}
}
//模拟生成文件id
function uuid(len, radix) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
var uuid = [], i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
</script>
</body>
</html>