js上传图片并易做图图片大小和尺寸源代码
<input type="file" accept="image/*" onchange="upImg(event)">js上传易做图上传图片尺寸
易做图上传图片大小
//易做图上传图片大小
if (upImgSize(e, 5)) {
// 易做图图片尺寸
upImgWH(e, 800, 800, function (flag) {
if (flag) {
upImg(e, '图片上传地址', function (data) {
console.log(data);
});
} else {
alert('上传图片的尺寸必须大于800*800')
}
})
} else {
alert('图片尺寸最大为5mb')
}
};
//上传图片到服务器
function upImg(e, url, callback) {
let file = e.target.files[0];
let formdata = new FormData();
formdata.append("file", file);
let xhr = new XMLHttpRequest();
xhr.open("post", url);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
callback && callback(JSON.parse(xhr.responseText));
}
};
xhr.onerror = function () {
alert("上传失败");
};
xhr.send(formdata);
},
//js上传易做图上传图片大小
function upImgSize(e, size = 5) {
let flag = false;
let file = e.target.files[0];
if (file.size <= 1024 * 1024 * size) {
flag = true;
} else {
flag = false;
}
console.log('易做图上传图片大小--该图片大小为:' + (file.size / (1024 * 1024)).toFixed(2) + '易做图');
return flag
},
//js上传易做图上传图片尺寸
function upImgWH(e, w = 800, h = 800, callback) {
let flag = false;
let file = e.target.files[0];
let url = window.URL.createObjectURL(file);
let image = new Image();
image.src = url;
image.onload = function () {
setTimeout(function () {
if (image.width >= w || image.height >= h) {
flag = true;
} else {
flag = false;
}
callback && callback(flag)
}, 1);
}
},