js原生文件上传


.upload-btn {
width: 96px;
height: 28px;
font-size: 12px;
font-family: PingFang SC-Regular, PingFang SC;
font-weight: 400;
color: #333333;
line-height: 16px;
margin-right: 12px;
cursor: pointer;
position: relative;
display: block;
overflow: hidden;
.cover{
background: #fff;
position: absolute;
width: 96px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
top: 0px;
left: 0;
border: 1px solid #BDBDBD;
border-radius: 3px 3px 3px 3px;
img {
width: 16px;
height: 16px;
margin-right: 4px;
}
svg{
fill: #999999;
margin-right: 4px;
}
&:hover{
color: #fff;
background-color: rgba(47, 127, 224, 1);
font-size: 12px;
svg{
fill: #fff;
}
}
}



}
<div class="upload-btn">
<input type="file" class="file" id="file"/>
<div class="cover">
<svg width="16" height="16" viewBox="0 0 16 16" fill="#999" xmlns="http://www.w3.org/2000/svg">
<path d="M14 7.5C14.2761 7.5 14.5 7.72386 14.5 8V14C14.5 14.2761 14.2761 14.5 14 14.5H2C1.72386 14.5 1.5 14.2761 1.5 14V8.00277C1.5 7.72662 1.72386 7.50277 2 7.50277C2.27614 7.50277 2.5 7.72662 2.5 8.00277V13.5H13.5V8C13.5 7.72386 13.7239 7.5 14 7.5Z"/>
<path d="M7.64645 1.64645C7.84171 1.45118 8.15829 1.45118 8.35355 1.64645L11.3536 4.64645C11.5488 4.84171 11.5488 5.15829 11.3536 5.35355C11.1583 5.54882 10.8417 5.54882 10.6464 5.35355L8 2.70711L5.35355 5.35355C5.15829 5.54882 4.84171 5.54882 4.64645 5.35355C4.45119 5.15829 4.45119 4.84171 4.64645 4.64645L7.64645 1.64645Z"/>
<path d="M7.99723 1.5C8.27338 1.5 8.49723 1.72386 8.49723 2V10.6667C8.49723 10.9428 8.27338 11.1667 7.99723 11.1667C7.72109 11.1667 7.49723 10.9428 7.49723 10.6667V2C7.49723 1.72386 7.72109 1.5 7.99723 1.5Z"/>
</svg>
点击上传
</div>
</div>


function fileHandler () {
// 1.获取标签
let file = document.getElementById('file');

// 2.监听图片选择的变化
file.onchange = function (e) {
const files = e.target.files
const rawFile = files[0] // only use files[0]
if (!rawFile) return
const isSize = rawFile.size / 1024 / 1024 < 25

// 3.判断文件大小
if (!isSize) {
//大于25m
console.log('大小超了')
return false;
}
// 4. 截取文件路径的名称
let suffix = rawFile.type

// 5. 判断文件类型
if (suffix.indexOf('zip') > -1 || suffix.indexOf('rar') > -1 || suffix.indexOf('7z') > -1) {
// to do 文件正确处理上传逻辑
console.log('对啦')
} else {
//文件类型不对
console.log('文件类型不对')
return false;
}
}
}
fileHandler();
posted @ 2022-10-05 21:50  szchenrong  阅读(186)  评论(0编辑  收藏  举报