// 单文件上传
upload: fileType => new Promise((resolve) => {
let elm = document.createElement('input');
elm.setAttribute('type', 'file'); // 根据文件类型设置可接收文件类别
switch (fileType) {
case 'image':
elm.setAttribute('accept', 'image/gif,image/jpeg,image/jpg,image/png,image/svg');
break;
case 'excel':
elm.setAttribute('accept', '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel');
break;
}
elm.style.display = 'none';
elm.addEventListener('change', async(e) => {
const file = e.target.files[0] || e.dataTransfer.files[0];
document.body.removeChild(elm);
elm = null;
resolve(file);
});
document.body.appendChild(elm);
elm.click();
})
// 多文件上传
uploads: fileType => new Promise((resolve) => {
let elm = document.createElement('input');
elm.setAttribute('type', 'file');
elm.setAttribute('multiple', 'multiple');
// 根据文件类型设置可接收文件类别
switch (fileType) {
case 'image':
elm.setAttribute('accept', 'image/gif,image/jpeg,image/jpg,image/png,image/svg');
break;
case 'excel':
elm.setAttribute('accept', '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel');
break;
}
elm.style.display = 'none';
elm.addEventListener('change', async(e) => {
const {
files,
} = e.target;
document.body.removeChild(elm);
elm = null;
resolve([...files]);
});
document.body.appendChild(elm);
elm.click();
})
JS 实现文件上传
于 2024-04-10 16:03:28 首次发布