第六节:实现拖拽上传
/* 拖拽上传 */
(function () {
let upload = document.querySelector('#upload6'),
upload_inp = upload.querySelector('.upload_inp'),
upload_submit = upload.querySelector('.upload_submit'),
upload_mark = upload.querySelector('.upload_mark');
let isRun = false;
// 实现文件上传
const uploadFile = async file => {
if (isRun) return;
isRun = true;
upload_mark.style.display = 'block';
try {
let fm = new FormData,
data;
fm.append('file', file);
fm.append('filename', file.name);
data = await instance.post('/upload_single', fm);
if (+data.code === 0) {
alert(`恭喜您,文件上传成功,您可以基于 ${data.servicePath} 访问该文件~~`);
return;
}
throw data.codeText;
} catch (err) {
alert(`很遗憾,文件上传失败,请您稍后再试~~`);
} finally {
upload_mark.style.display = 'none';
isRun = false;
}
};
// 拖拽获取 dragenter dragleave dragover drop
/* upload.addEventListener('dragenter', function () {
console.log('进入');
});
upload.addEventListener('dragleave', function () {
console.log('离开');
}); */
upload.addEventListener('dragover', function (ev) {
ev.preventDefault();
});
upload.addEventListener('drop', function (ev) {
ev.preventDefault();
let file = ev.dataTransfer.files[0];
if (!file) return;
uploadFile(file);
});
// 手动选择
upload_inp.addEventListener('change', function () {
let file = upload_inp.files[0];
if (!file) return;
uploadFile(file);
});
upload_submit.addEventListener('click', function () {
upload_inp.click();
});
})();