在使用​​​​上传图片时,若图片过大,则无法上传成功。

我们需要通过压缩图片大小再上传来解决这个问题。

代码示例如下:

HTML:

<ul class="ul-upload">
<li></li>
<li></li>
</ul>
<form id="uploadForm" method="post" enctype="multipart/form-data">
<input type="file" id="uploadFile" name="uploadFile">
</form>

JS:

$(".ul-upload li").click(function() {
$("#uploadFile").click();
});

$("#uploadFile").change(function() {
var val = $(this).val();
if (val != null && val != '') {
var temp = val.substring(val.indexOf(".") + 1);
if (temp == 'png' || temp == 'jpg') {
var fileObj = document.getElementById("uploadFile").files[0]; // js
var form = new FormData(); // FormData 对象
imgCallBack(fileObj,form)
} else {
alert("请选择后缀为png、jpg的图片上传!")
}
}
});

function imgCallBack(fileObj,form) {
if (fileObj.size / 1024 > 1025) { // 大于1M,进行压缩上传
photoCompress(fileObj, {
quality : 0.2
}, function(base64Codes) {
var bl = convertBase64UrlToBlob(base64Codes);
form.append("file", bl, "file_" + Date.parse(new Date()) + ".jpg"); // 文件对象
$.ajax({
url :'',
type : 'POST',
data : form,
async : false,
cache : false,
contentType : false,
processData : false,
success : function(data) {

}
});
});
} else {
form.append("file", fileObj); // 文件对象
$.ajax({
url :'',
type : 'POST',
data : form,
async : false,
cache : false,
contentType : false,
processData : false,
success : function(data) {

}
});
}
}

function photoCompress(file, w, objDiv) {
var ready = new FileReader();
ready.readAsDataURL(file);
ready.onload = function() {
var re = this.result;
canvasDataURL(re, w, objDiv)
}
}

function canvasDataURL(path, obj, callback) {
var img = new Image();
img.src = path;
img.onload = function() {
var that = this;
// 默认按比例压缩
var w = that.width, h = that.height, scale = w / h;
w = obj.width || w;
h = obj.height || (w / scale);
var quality = 0.7; // 默认图片质量为0.7
// 生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 创建属性节点
var anw = document.createAttribute("width");
anw.nodeValue = w;
var anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
// 图像质量
if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
quality = obj.quality;
}
// quality值越小,所绘制出的图像越模糊
var base64 = canvas.toDataURL('image/jpeg', quality);
// 回调函数返回base64的值
callback(base64);
}
}

function convertBase64UrlToBlob(urlData) {
var arr = urlData.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 Blob([u8arr], {
type : mime
});
}