版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Hello_Java2018/article/details/84027567
运用js进行对图片的压缩上传
1.html片段
<label class="font-size-normal mar-top20" ><div style="width: 4px;height: 25.4px;background-color: #ffc002; float: left;border-radius:4px;"></div> 图片上传</font></label>
<input type="hidden" name="imgs" id="imgs" value="">
<input type="file" multiple="multiple" id="multiple" />
<div id="box"></div>
<input type="file" multiple="multiple" id="multiple" />
<div id="box"></div>
1.js片段片段
<script>
var j = 1;
// 多张
$('#multiple').on('change', function (e) {
var
i = 0,
files = e.target.files,
len = files.length,
notSupport = false;
// 循环多张图片,需要for循环和notSupport变量支持(检测)
for (; i < len; i++) {
if (!notSupport) {
(function(i) {
new html5ImgCompress(files[i], {
before: function(file) {
console.log('多张: ' + i + ' 压缩前...');
},
done: function (file, base64) { // 这里是异步回调,done中i的顺序不能保证
console.log('多张: ' + i + ' 压缩成功...');
// insertImg(file, j);
insertImg(base64, j++);
upload(base64);
},
fail: function(file) {
console.log('多张: ' + i + ' 压缩失败...');
},
complete: function(file) {
console.log('多张: ' + i + ' 压缩完成...');
},
notSupport: function(file) {
notSupport = true;
alert('浏览器不支持!');
}
});
})(i);
}
}
});
function upload(file){
$.ajax({
type: 'POST',
url: '/upload',
data: {
"base64": file,
},
dataType : "JSON",
success: function(date) {
$("#imgs").val($("#imgs").val() + date.badge + ",");
},
error : function() {
console.info('err');
}
});
}
// html中插入图片
function insertImg(file, j) {
var
img = new Image(),
title, src, size, base;
if (typeof file === 'object') {
} else {
title = '后';
size = file.length;
src = file;
base = 1333;
}
if (!$('.box_' + j).length) {
$('#box').prepend('<div class="box_' + j + '" />'); // 逆序,方便demo多次上传预览
}
img.onload = function() {
$('.box_' + j).prepend(img).prepend('<p>图片' + j + ',处理' + title + '</p><p>质量约:<span>' + (size / base).toFixed(2) + 'KB</span>' + ' 尺寸:<span>' + this.width + '*' + this.height + '</span></p>');
};
img.src = src;
file = null; // 处理完后记得清缓存
};
</script>