<!DOCTYPE html>
<html>
<head>
<meta charset=
"UTF-8"
>
<meta name=
'viewport'
content=
'width=device-width, initial-scale=1, maximum-scale=1'
>
<title>lianxi </title>
<style type=
"text/css"
>
</style>
</head>
<body>
<form>
名字:<input type=
"text "
name =
'username'
id =
'username'
/>
上传:<input type=
"file"
name =
'fileimage'
id =
'fileimage'
/>
</form>
<button>button</button>
<script>
var
file = document.querySelector(
'#fileimage'
)
var
username = document.querySelector(
'#username'
)
var
canvas = document.createElement(
'canvas'
);
var
span = document.createElement(
'span'
)
var
formData =
new
FormData()
file.addEventListener(
'change'
,
function
() {
span.innerHTML =
'预览图加载中...'
document.body.appendChild(span)
console.log(file.files[0])
username.value ? formData.append(
'username'
,username.value) : null;
resize(file.files[0]);
})
function
resize(file) {
var
reader =
new
FileReader()
reader.readAsDataURL(file)
var
img =
new
Image()
reader.onload =
function
(e) {
img.src = this.result;
}
var
context = canvas.getContext(
'2d'
);
var
gif = document.createElement(
'img'
)
img.onload =
function
() {
if
(img.width > 300 || img.height > 300) {
if
(img.width > img.height) {
canvas.width = 300
canvas.height = img.height / img.width * 300
}
else
{
canvas.height = 300
canvas.width = img.width / img.height * 300
}
}
context.drawImage(img, 0, 0, canvas.width, canvas.height)
document.body.removeChild(span)
document.querySelector(
'body'
).appendChild(canvas)
};
}
document.querySelector(
'button'
).addEventListener(
'click'
,
function
(){
canvas.toBlob(
function
(blob){
var
xhr =
new
XMLHttpRequest()
formData.append(
'fileimage'
, blob,
'002.webp'
)
xhr.open(
'POST'
,
'test.php'
, true)
xhr.upload.addEventListener(
'progress'
,
function
(e) {
console.log(
'上传进度为:'
+ (e.loaded/e.total*100).toFixed(2)+
'%'
)
})
xhr.upload.addEventListener(
'loadstart'
,
function
() {
console.log(
'上传开始'
)
})
xhr.onreadystatechange =
function
() {
if
(xhr.readyState === 4) {
if
(xhr.status >= 200 && xhr.status <300 || xhr.status == 304) {
console.log(JSON.parse(xhr.responseText))
}
else
{
console.log(
"Request was unsuccessful: "
+ xhr.status);
}
}
}
xhr.send(formData)
},
'image/webp'
,0.9)
})
</script>
</body>
</html>