<!DOCTYPE html
>
<html
>
<head
>
<meta charset
="UTF-8">
<title
>前端压缩上传图片
</title
>
<script src
="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script
>
</head
>
<style
>
.outer
{
width
: 100%;
height
: 100%;
}
.update
{
position
: absolute
;
top
: 34%;
left
: 10%;
width
: 80%;
height
: 49%;
}
.update input
{
position
: absolute
;
top
: 0;
left
: 0;
width
: 100%;
height
: 100%;
opacity
: 0;
}
.update img
{
width
: 100%;
height
: 100%;
}
</style
>
<body
>
<div class
="outer">
<div class
="update">
<input type
="file" id
="picFile" onchange
="readFile(this)"/>
<img id
="img" src
="https://sucai.suoluomei.cn/sucai_zs/images/20191028141957-tinjai.png" alt
=""/>
</div
>
</div
>
<script
>
function readFile(obj
) {
var file
= obj
.files
[0];
if (!/image\
/\w
+/.test(file
.type
)) {
alert("请确保文件为图像类型");
return false;
}
var reader
= new FileReader();
reader
.readAsDataURL(file
);
reader
.onload
= function (e
) {
dealImage(this
.result
, {quality
: 0.5}, function (base
) {
var blob
= dataURLtoBlob(base
);
var newFile
= new File([blob
], file
.name
, {type
: file
.type
});
console
.log(newFile
)
let r
= new FileReader();
r
.onload
= function () {
;
}
r
.readAsDataURL(newFile
);
upload(newFile
);
});
}
}
function dataURLtoBlob(dataurl
) {
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 Blob([u8arr
], {type
: mime
});
}
function upload(file
) {
var that
= this
;
let param
= new FormData();
param
.append('file', file
);
param
.append("key", "Gn1xVdBiTClSSHKZifg0pTQSU5XGagWO");
for (var n
in that
.params
) {
param
.append(n
, that
.params
[n
]);
}
var xhr
= new XMLHttpRequest();
xhr
.onload
= function (res
) {
console
.log(xhr
.responseText
)
let res1
= JSON
.parse(res
.currentTarget
.response
)
console
.log("我是谁,我在哪儿?",JSON
.parse(res
.currentTarget
.response
))
$
('#img').attr('src', res1
.info
.url
)
}
xhr
.open("POST", "http://api110.herbplantist.com/sucai/public/index.php/post/post/uploadFile", true);
xhr
.send(param
);
}
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
= obj
.quality
|| 0.7;
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
;
}
var base64
= canvas
.toDataURL('image/jpeg', quality
);
callback(base64
);
}
}
</script
>
</body
>
</html
>
转载请注明原文地址: https://mac.8miu.com/read-492755.html