前端使用Compressor进行图片压缩使用示例
在这里前端浏览器就对图片进行压缩掉,可以减少数据传输,减少后台存储.主要用到了compressorjs
效果
https://fengyuanchen.github.io/compressorjs
这里贴出主要的代码
<div class="mui-card">
<div class="">
<div class="mui-button-row" style="border-bottom: #E3E3E3 dashed 1px">
<label style="padding-top:5px;">附件上传</label>
<button type="button" class="mui-btn mui-btn-danger mui-btn-outlined" onclick="choseFileUploadSelect(2);">文件上传</button>
<button type="button" class="mui-btn mui-btn-primary mui-btn-outlined" onclick="choseFileUploadSelect(1);">拍照上传</button>
</div>
<!--图片预览层-->
<div >
<form id="frm" >
<!-- <div style="height:105px;width:1px;float:left"><!–占位用的–></div>-->
<ul class="file_ul" id="file_ul" style="background-color: #efefef !important;">
</ul>
<div style="margin:10px 5px 10px 5px;height:100px;width:100px; display: inline;float:left;"><!--占位用的-->
<img onclick="choseFileUploadSelect(2);" class="img-thumbnail" style="width: 120px"
src="../images/fileupts.png"
/>
</div>
</form>
</div>
</div>
</div>
基本样式css
.file_ul li{
float:left;
/* z-index: 9998;*/
margin-top:10px;
margin-bottom:5px;
margin-right:2px;
width:105px;
height:105px;
}
.file_li {
list-style-type: none;
}
.imgDiv .close {
opacity: 1;
color: red;
/*color: #333333;*/
border-radius: 12px;
line-height: 20px;
text-align: center;
height: 20px;
width: 20px;
font-size: 26px;
padding: 0.5px;
top: -8px;
right: 0px;
position: absolute;
/*z-index: 9998 !important;*/
}
.imgDiv1 .close1::before {
opacity: 1;
content: "\2716";
}
引用库
<script th:src="@{/js/jquery-3.5.0.min.js}" type="text/javascript" charset="utf-8"></script>
<script th:src="@{/js/plugins/layer/layer.js}" type="text/javascript"></script>
<script th:src="@{/js/plugins/compressorjs/compressor.js}" type="text/javascript" charset="utf-8"></script>
var k=0;
function choseFileUploadSelect(fs){
k++;
var id = "file_" + k;
if (fs==1) {
var input = document.createElement('input'); //创建input节点
input.setAttribute('id', id); //添加id
input.setAttribute('type', 'file'); //定义类型是文本输入
input.setAttribute('name', 'file');//添加name
input.setAttribute('accept', 'image/*');//添加name
input.setAttribute('capture', 'camera');//添加name
input.setAttribute('style', 'display:none');//添加隐藏样式
input.setAttribute('onchange', 'fileImageSelectUpload("'+id+'")');//设置触发方法
input.setAttribute('onkeydown', 'return false');//设置只允许上传一张
document.getElementById('frm').appendChild(input); //添加到form中显示
document.getElementById(id).click();
}else{
var input = document.createElement('input'); //创建input节点
input.setAttribute('id', id); //添加id
input.setAttribute('type', 'file'); //定义类型是文本输入
input.setAttribute('name', 'file');//添加name
input.setAttribute('accept', 'image/*');//添加name
input.setAttribute('style', 'display:none');//添加隐藏样式
input.setAttribute('onchange', 'fileImageSelectUpload("'+id+'")');//设置触发方法
input.setAttribute('onkeydown', 'return false');//设置只允许上传一张
document.getElementById('frm').appendChild(input); //添加到form中显示
document.getElementById(id).click();
}
}
//选择文件并生成对应的文件名
function fileImageSelectUpload(id){
console.log(id);//file0 file1
console.log("-------");
var file = $("#"+id).val();
if(file == ""){
layer.msg("未选择文件!");
return;
}
var fileName = file.replace(/^.+?\\([^\\]+?)(\.[^\.\\]*?)?$/gi,"$1");
console.log(fileName);
var type=file.substring(file.lastIndexOf(".")).toLowerCase();
if(type==""){
layer.msg("选取文件有误,文件类型未知!");
return ;
}else {
if (!/\.(bmp|BMP|jpg|jpeg|png|JPG|JPEG|PNG)$/.test("."+type)) {
layer.msg("文件类型有误!");
return ;
}
var file1=document.getElementById(id);
//压缩 上传成功 显示 上传不成功不显示
var fileNoZip= file1.files[0];//$("#fileK1").get(0).files[0];//this.files[0];
console.log("压缩前大小:"+fileNoZip.size);
//创建本地显示对象
var objUrl = getObjectURL(fileNoZip);
if (objUrl) {
var file_li_id='file_li_'+k;
var img_name="img"+k;//
var img_nameTest="img\""+k;
var fsize=fileNoZip.size;
//换算为mb
var fsizeMb=Math.trunc( fsize/1024/1024);
//默认压缩比列
var qualityJs=0.1;
if( fsizeMb<=1 ){
qualityJs=1; //小于等 1mb不压缩
}else {
qualityJs = Math.trunc(1 / (fsize / 1024 / 1024) * 100) * 0.01;
console.log("计算得图片质量 压缩比:"+qualityJs);
}
//压缩文件
new Compressor(fileNoZip, {
quality: qualityJs,
success(result) {
//result 是一个文件对象
console.log("压缩成功...");
// console.log(result);
console.log("压缩后大小:" + result.size)
//压缩成功上传文件
var fd = new FormData();
fd.append("file1", result,result.name);
$(".loadingToastFileUp").show();
$.ajax({
url : basePath+"/fileImgUpload",
type : "POST",
processData : false,
contentType : false,
dataType : "json",
data : fd,
success : function(data) {
$(".loadingToastFileUp").hide();
if (data.code=="9999") {
layer.msg("上传成功。");
$('.file_ul').append(
'<li class="file_li" id="'+file_li_id+'" data-id="">'
+'<div class="imgDiv"style="height: 100px; width: 100px; border: 1px solid #e3e4e5; position: relative;">'
+'<img id="'+img_name+'" style="width: 100px;height: 100px;" data-mymc="mymc-'+img_nameTest+'" onclick="showImg(this)"></img>'
+'<span class="close mui-icon mui-icon-close" style="color:red;" onclick="deleteImg_li('+k+');"></span>'
+'</div>'
+'</li>');
$('#'+file_li_id).data("id",data.id);
console.log("取出ID==",$('#'+file_li_id).data("id"));
//var previewZipObjUrl = getObjectURL(result);
var preview = document.querySelector('#'+img_name);
// preview.src=previewZipObjUrl;//为压缩过后的返回base64图片内容
preview.src=objUrl;//用原图显示
}else{
layer.msg("上传失败。");
}
},
error : function(xhr, ajaxOptions, thrownError) {
$(".loadingToastFileUp").hide();
layer.alert("上传异常:" + xhr.status +";"+ thrownError);
}
});
},
error(e) {
console.log("压缩出错.");
console.log(e.message);
},
})
}
}
}
后台接收
//文件上传
@RequestMapping("/fileImgUpload")
@ResponseBody
protected JSONObject fileImgUpload(HttpServletRequest request, HttpServletResponse response)
throws ServletException, Exception {
// 获取文件部件part
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 获得文件:
MultipartFile part = multipartRequest.getFile("file1");
Long wjdx=part.getSize();
String filenameUp = part.getOriginalFilename();
String ext = filenameUp.substring(filenameUp.lastIndexOf("."), filenameUp.length());
String filename = FileCommonUtils.getNewFileName() + ext;
String filenamePath = "d:\" + File.separator + filename;
part.transferTo(new File(filenamePath));
....
}