作者:你看我的泪 | 来源:互联网 | 2023-10-12 09:15
单文件压缩上传
<input type="file" id="file">
构造函数
function UpFileImg(options){
var optiOns= options || {
el:'',
compressSize:640,
datatype:'base64',
success:function(val){}
};
var that = this;
// 读取文件
this.setFilesReader = function(file){
var reader = new window.FileReader();
var fileSize = Math.round(file.size/1024/1024);
var that = this;
reader.readAsDataURL(file);
reader.onload = function(e) {
that.compress(this.result,fileSize);
};
};
// 压缩文件
this.compress = function(res, fileSize){
var img = new Image();
var maxW = options.compressSize; //压缩后大小
var that = this;
img.src = res;
img.onload = function () {
var cvs = document.createElement('canvas'), ctx = cvs.getContext('2d');
if(img.width > maxW) {
img.height *= maxW / img.width;
img.width = maxW;
}
cvs.width = img.width;
cvs.height = img.height;
ctx.clearRect(0, 0, cvs.width, cvs.height);
ctx.drawImage(img, 0, 0, img.width, img.height);
// 设置压缩比
var compressRate = that.getCompressRate(1,fileSize);
// 压缩
var dataUrl = cvs.toDataURL('image/jpeg', compressRate);
if(options.datatype === 'blob'){
var dataUrl = that.dataURItoBlob(dataUrl);
}
// 成功后回调
that.compressCallblak(options.success,dataUrl);
};
};
// 压缩后回调函数
this.compressCallblak = function(fun,val){
fun(val);
};
// 计算压缩比
this.getCompressRate = function(allowMaxSize,fileSize){
var compressRate = 1;
if(fileSize/allowMaxSize > 4){
compressRate = 0.5;
} else if(fileSize/allowMaxSize >3){
compressRate = 0.6;
} else if(fileSize/allowMaxSize >2){
compressRate = 0.7;
} else if(fileSize > allowMaxSize){
compressRate = 0.8;
} else{
compressRate = 0.9;
}
return compressRate;
};
//base64转blob
this.dataURItoBlob = function(base64Data){
var byteString;
if (base64Data.split(',')[0].indexOf('base64') >= 0){
byteString = atob(base64Data.split(',')[1]);
}
else{
byteString = unescape(base64Data.split(',')[1]);
}
var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
var ia = new Uint8Array(byteString.length);
for (var i = 0; i ) {
ia[i]
=
byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
document.getElementById(options.el).onchange =
function (){
var f =
this.files[0
];
that.setFilesReader(f);
};
};
示例:(转为blob对象后使用ajax上传)
var fileImg = new UpFileImg({
el:'file', //绑定id
compressSize:700, //默认640
datatype:'blob', //默认转换为base64
success:function(data,name){
// 回调
console.log(data);
console.log(name);
var fd = new FormData();
// file_key为上传文件后台对应的key也就相当于input的name,
// data为bolo对象,
// name为上传文件的名称
fd.append("file_key", data, name);
$.ajax({
url: '上传地址',
type: 'POST',
data: fd,
processData: false, // 必须
contentType: false, // 必须
dataType: 'json',
success:function(data){
console.log(data);
}
});
}
});
名称 |
默认值 |
是否必传 |
描述 |
el |
无 |
是 |
对应input的ID |
compressSize |
640 |
否 |
压缩后最大宽度 |
datatype |
base64 |
否 |
回调函数返回值类型,默认返回base64,可以设置为blob,配合ajax进行上传 |
success |
无 |
是 |
回调函数返回文件名称,与压缩后文件(base64或者blob) |