Add upload progress support

This commit is contained in:
yulai.li 2022-04-07 14:23:06 +08:00
parent 4f87ee7755
commit 2454020a92

View file

@ -44,6 +44,25 @@
border-radius: 2px;
}
.footer {
position: absolute;
bottom: 10px;
right: 10%;
min-width: 30%;
}
.progress-table {
width: 100%;
}
.progress-table-file-name {
text-align: right;
}
.progress-table-percent {
width: 60px;
text-align: right;
}
</style>
</head>
<body>
@ -62,7 +81,7 @@
</a>
{{ end }}
<label class="button" for="fileElem">Upload</label>
<label class="button" onclick="handleCreateDir()">Create Dir</label>
<label class="button" onclick="handleCreateDir()">New Folder</label>
</div>
</div>
@ -125,12 +144,14 @@
<br/>
<br/>
<div id="progress-area" class="footer" style="display: none;">
</div>
</div>
</body>
<script type="text/javascript">
// ************************ Drag and drop ***************** //
let dropArea = document.getElementById("drop-area");
let progressArea = document.getElementById("progress-area");
// Prevent default drag behaviors
;['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
@ -170,18 +191,71 @@
handleFiles(files);
}
var uploadList = {};
function handleFiles(files) {
files = [...files];
files.forEach(startUpload);
renderProgress();
files.forEach(uploadFile);
window.location.reload();
}
function startUpload(file, i) {
uploadList[file.name] = {'name': file.name, 'percent': 0, 'finish': false};
}
function renderProgress() {
var values = Object.values(uploadList);
var html = '<table class="progress-table">\n';
for (let i of values) {
html += '<tr>\n<td class="progress-table-file-name">' + i.name + '</td>\n';
html += '<td class="progress-table-percent">' + i.percent + '% </td>\n</tr>\n';
}
html += '</table>\n';
progressArea.innerHTML = html;
if (values.length > 0) {
progressArea.attributes.style.value = '';
}
console.log('Render Progress', values);
}
function reportProgress(file, percent) {
var item = uploadList[file]
item.percent = percent;
renderProgress();
}
function finishUpload(file) {
uploadList[file]['finish'] = true;
renderProgress();
var allFinish = true;
for (let i of Object.values(uploadList)) {
if (!i.finish) {
allFinish = false;
break;
}
}
if (allFinish) {
console.log('All Finish');
window.location.reload();
}
}
function uploadFile(file, i) {
var url = window.location.href;
var xhr = new XMLHttpRequest();
var fileName = file.name;
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
var percent = Math.ceil((e.loaded / e.total) * 100);
reportProgress(fileName, percent)
}
});
xhr.upload.addEventListener('loadend', function(e) {
finishUpload(fileName);
});
var formData = new FormData();
xhr.open('POST', url, false);
xhr.open('POST', url, true);
formData.append('file', file);
xhr.send(formData);
}