為了節約網絡資源多數圖檔上傳的時候需要進行一下壓縮
這裡寫一下通過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>