jq中实现图片压缩、base64转成file后上传至服务器示例
有项目中需要实现把图片压缩、base64编码转file文件等功能,然后再上传至服务器。
下面是直接在jq中实现上述功能。
示例代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<input type="file" id="picFile" onchange="readFile(this)" />
<img style="" id="img" src="" alt="" />
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script language="javascript">
function readFile(obj){
maxSize = 2*1024*1024;
var file = obj.files[0];
if(file.size < maxSize){
alert('小于2m直接上传');
upload(file);
return false
}
console.log(file)
//判断类型是不是图片
if(!/image\/\w+/.test(file.type)){
alert("请确保文件为图像类型");
return false;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e){
dealImage(this.result,{width:750},function(base){
document.getElementById('img').setAttribute('src',base)
var file = dataURLtoFile(base,'test.jpg')
upload(file);
});
}
}
function upload(file)
{
var formData = new FormData();
formData.append('img_url', file);
$.ajax({
url: 'https://www.zongscan.com/h5_upload.php',
type: 'POST',
cache: false,
data: formData,
dataType: "JSON",
processData: false,
contentType: false,
success: (res) => {
console.log(res)
}
}).done(function(res) {
}).fail(function(res) {
});
}
//base64 转 file
//filename 上传文件名(需含扩展名)
function dataURLtoFile(dataurl, filename) {
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});
}
/* 图片压缩,默认同比例压缩
* @param {Object} path
* pc端传入的路径可以为相对路径,但是在移动端上必须传入的路径是照相图片储存的绝对路径
* @param {Object} obj
* obj 对象 有 width, height, quality(0-1)
* @param {Object} callback
* 回调函数有一个参数,base64的字符串数据
*/
function dealImage(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 = 1; // 默认图片质量为0.7
console.log(w,h)
var canvas = document.createElement('canvas');//生成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);
}
}
</script>
</body>
</html>
相关文章