为了节约网络资源多数图片上传的时候需要进行一下压缩
这里写一下通过canvas方式进行压缩
就直接贴代码吧
注释掉的部分是JQuery上传文件的方法
<!DOCTYPE html>
<html>
<head>
<title>上传图片</title>
<style type="text/css">
.btn{
background: #18bc93;
padding: 5px 13px;
color: #fff;
border: none;
font-size: 16px;
}
div{
margin-top: 15px;
}
div{
text-align: center;
}
</style>
</head>
<body>
<div>
<label class='btn'>
选择图片
<input type="file" onchange="showImg(this)" id="uploadInput" value="" accept="image/png,image/jpeg,image/jpg" style="display: none">
</label>
</div>
<div>
<img src="" width="500" height="300" style="display: none" id="img0">
<canvas width="500" height="300" id="canvas"></canvas>
</div>
<div>
<button class="btn" onclick="uploadImg()">上传图片</button>
</div>
<script type="text/javascript">
// 图片预览
function showImg(self){
let objUrl = getObjectURL(self.files[0]) ;//获取文件信息
if (objUrl) {
document.getElementById("img0").src = objUrl;
document.getElementById("img0").style = "display:inline";
}
}
// 获取路径
function getObjectURL(file) {
let url = null;
if (window.createObjectURL!=undefined) {
url = window.createObjectURL(file) ;
} else
if (window.URL!=undefined) {
url = window.URL.createObjectURL(file) ;
} else
if (window.webkitURL!=undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}
// 图片压缩上传
function uploadImg(){
let imgData = new FormData(); // 创建FormData()对象用于文件上传
let canvas = document.getElementById("canvas"); // 获取画板
let context = canvas.getContext("2d");
context.drawImage(document.getElementById("img0"),0,0, 500,300);
imgBase64 = canvas.toDataURL("image/jpeg");
imgData.append("img",dataURLtoFile(imgBase64,"1"));
console.log(imgBase64);
// $.ajax({
// url:"",
// data:imgData,
// cache: false, //上传文件不需要缓存
// processData: false, // 告诉jQuery不要去处理发送的数据
// contentType: false, // 告诉jQuery不要去设置Content-Type请求头
// type:"post",
// dataType:"json",
// success:function (data) {
// if(data.success == true){
// alert("上传成功!");
// }else{
// alert("上传失败!");
// }
// },
// error:function (data) {
// alert("上传失败!");
// }
// })
}
function dataURLtoFile(dataurl, filename) {//将base64转换为文件
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
</script>
</body>
</html>