以为目前没有找到原声javascript的方法进行替换所以我们还是引入了jquery
一,引入jquery
二,界面展示
三,压缩上传的逻辑
function Upload() {
setTimeout(function () {
UploadMethod();
},100)
}
function UploadMethod() {
const imgPath = document.getElementById("idCardFront").value;
console.log("正面的图片地址:imgPath="+imgPath);
if (imgPath == '') {
return;
}
//判断上传文件的后缀名
const strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1);
if (strExtension != 'jpeg' && strExtension != 'jpg' && strExtension != 'gif'
&& strExtension != 'png' && strExtension != 'bmp'&&strExtension != 'JPG' && strExtension != 'GIF'
&& strExtension != 'PNG' && strExtension != 'BMP') {
console.log('请选择图片文件');
return;
}
const file = $("#idCardFront").prop('files')[0];
if(file.size > 10 * 1024 * 1024){//如果大于10MB就重新选择图片
console.log('图片大小超过10M,请重新选择');
return;
}
photoCompress(file, function (base64Codes) {
let xhr="";
const url = "https://***/upload"; // 接收上传文件的后台地址
const form = new FormData(); // FormData 对象
const bl = convertBase64UrlToBlob(base64Codes);
form.append("uploadFile", bl, "file_"+Date.parse(new Date())+".png"); // 文件对象
xhr = new XMLHttpRequest(); // XMLHttpRequest 对象
xhr.open("post", url, true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。
xhr.onload = function (evt) {
//服务断接收完文件返回的结果
console.log(evt);
const res = JSON.parse(evt.target.responseText);
if (res.status == "success") {
console.log("上传成功:res.result="+res.result);
document.getElementById("showImg").src=base64Codes;
} else {
console.log(res.message);
}
}; //请求完成
xhr.onerror = function (evt) {
console.log("上传失败")
}; //请求失败
xhr.send(form); //开始上传,发送form数据
});
}
/*
两个参数
file:一个是文件(类型是图片格式),
objDiv:一个是容器或者回调函数
*/
function photoCompress(file, objDiv) {
const ready = new FileReader();
/*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
ready.readAsDataURL(file);
ready.onload = function () {
const re = this.result;
const w={
quality:300/(10*1024)
}
canvasDataURL(re, w,file, objDiv)
}
}
function canvasDataURL(path, obj,file, callback) {
const img = new Image();
img.src = path;
img.onload = function () {
/* 按图片缩小宽高完成图片压缩(未启用) */
const that = this;
let w = that.width,
h = that.height;
//生成canvas
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const anw = document.createAttribute("width");
anw.nodeValue = w;
const anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
/* 按图像质量压缩(启用) */
// quality值越小,所绘制出的图像越模糊。用图片质量压缩
let quality = 0.7; // 默认图片质量为0.7
if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
quality = obj.quality;
}
if(file.size<=300*1024){
quality=1;
}
/* 最后将图片转换成base64 */
const base64 = canvas.toDataURL('image/jpeg', quality);
callback(base64);//回调
}
}
/**
* 将以base64的图片url数据转换为Blob,用于form表单上传
* @param urlData
* 用url方式表示的base64图片数据
*/
function convertBase64UrlToBlob(urlData){
let arr = urlData.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});
}