有些时候上传图片到服务器有明确的格式要求,现在讲讲如何制作上传图片及转为blob与base64格式
base64优缺点:
优点:
- base64格式占用内存小,图片转为base64后只为原图三分之一
- base64图片减少了对服务器的请求
- base64是字符串类型,更适合多平台,多语言使用
缺点:
- base64字符串内容多,给数据库压力大
- base64由于内容多,网页加载会比较缓慢
<!DOCTYPE html>
<html lang="zh-ch">
<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>
<style>
.box{
width: 200px;
height: 200px;
border: 1px dashed gainsboro;
text-align: center;
position: relative;
cursor: pointer;
}
.box:hover{
border: 1px dashed rgb(0, 183, 255);
}
strong{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
font-size: 80px;
font-weight: 500;
color: rgb(126, 126, 126);
}
input{
display: none;
}
img{
width: 100%;
}
</style>
</head>
<body>
<div class="box">
<strong>+</strong>
<img src="" alt="">
</div>
<input type="file" >
</body>
<script>
const box = document.querySelector('.box')
const input = document.querySelector('input')
const strong = document.querySelector('strong')
const img = document.querySelector('img')
box.onclick=function(){
input.click();
}
input.onchange = function(e){
const file = e.target.files[0]
// 为了转为base64,图片太大导致页面加载缓慢,字符体积大等问题
if (file.size / 1024 / 1024 > 1.5) {
return this.$message.warning('图片大小不能大于1.5M')
}
const fileReader = new FileReader()
const imgUrl = URL.createObjectURL(file)
// 转blob格式图片
console.log(imgUrl,0);
// console.log(fileReader,111);
fileReader.readAsDataURL(file)
fileReader.addEventListener('load', () => {
// console.log(fileReader.result,222)
// 注意this指向问题,用箭头函数避免指向该函数
// 转base64格式图片
console.log(fileReader.result,333);
// this.imageUrl = fileReader.result
if(fileReader.result){
img.attributes.src.value = fileReader.result
strong.style.display = 'none'
}
})
}
</script>
</html>
基础代码没做优化处理,样式优点乱,见谅!!!