<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id='sisui'>
<input class="file" type="file" style="display: none;" multiple />
<button class="inpButton">点击选择</button>
<button class="inpButton_Ok">确定上传</button>
<ul class="inpUl" style="display: none;">
</ul>
</div>
<script>
let inpSisui = document.getElementById('sisui')
inpFile = inpSisui.querySelector('.file')
inpButton = inpSisui.querySelector('.inpButton')
inpButtonOk = inpSisui.querySelector('.inpButton_Ok')
inpUiList = inpSisui.querySelector('.inpUl')
let _file = [] //存放选中的文件
let url_New = '定义的网站网址'
// 确定上传
inpButtonOk.addEventListener('click',function(){
if(_file.length >0){
console.log('这是确定上传的',_file)
// 循环发送请求
// _file = _file.map(item=>{
// let fm = new FormData;
// fm.append('file',item.file);
// fm.append('fileName',item.flieNam);
// // 每循环一次就调用接口
// // return url_New.post('/接口',fm,{
// // onUploadProgress(e){
// // //检测每一个文件的上传进度
// // let newSum = `${(e.loaded/e.total*100).toFixed(2)}%`
// // console.log('当前上传进度:',newSum)
// // }
// // }).then(data=>{
// // if(data.code === 0){
// // return console.log('上传后的返回',data)
// // }
// // return Promise.reject()
// // })
// })
}else{
console.log('请选择文件')
}
})
// 这是选中的展示
inpUiList.addEventListener('click',function(e){
let target = e.target;
curLi = null; //存放父类
key=null;
console.log('e',e)
console.log('e.target',e.target)
console.log('e.target.tagName',e.target.tagName)
if(target.tagName === 'EM'){
curLi = target.parentNode.parentNode;
if(!curLi) return;
key = curLi.getAttribute('key')
inpUiList.removeChild(curLi)
_file = _file.filter(item=>item.key !== key)
}
})
//定义一个随机数唯一值 用作 li 标签的key
const createRandom = ()=>{
let ran = Math.random()*new Date()
return ran.toString(16).replace('.','')
}
inpFile.addEventListener('change', function () {
_file = Array.from(inpFile.files)
_file = _file.map(ele=>{
return{
file:ele,
flieNam:ele.name,
key:createRandom()
}
})
let str = ``;
if (_file.length === 0) return alert('请选择文件')
_file.forEach((ele,index) => {
str += `
<li key="${ele.key}">
<span>文件${index}:${ele.flieNam}</span>
<span><em style="margin-left:10px;color:red;">删除</em></span>
</li>`
})
inpUiList.innerHTML = str
inpUiList.style.display = 'block';
})
inpButton.addEventListener('click', function () {
inpFile.click()
})
</script>
</body>
</html>
js原生文件上传
最新推荐文章于 2024-06-04 17:35:28 发布