Layui front-end upload module

Layui to use at work, I found that the upload function is not very suitable for their own projects. Therefore, to borrow upload function, compress and upload your own picture.

Layui upload pictures official document: https: //www.layui.com/doc/modules/upload.html

HTML: 

<the Button of the type = "the Button" class = "layui-btn" the above mentioned id = "test1">
<i class = "layui-icon"> & # xe67c; </ i> Photo
</ the Button>
Tips: do not have to be the input tag, no matter what the label, layui upload is operating in accordance with its id value

JS:  

<Script>
// use layui Photo
layui.use ( 'Upload', function () {
var = Upload layui.upload;
var = layui.layer Layer;

// execution instance
var uploadInst = upload.render ({
elem: ' #isTest ', // binding element
url:' / upload / ', // Upload Interface
Accept:' Images',
Auto: to false,

the choose: function (obj) {// file selection callback
var files = obj. pushFile ();
var filesArry = [];
for (var in Key files) {// upload files into an array
filesArry.push (files [Key])
}
var index = filesArry.length -. 1;
var file = filesArry [index]; // Gets the last selected picture, that deal with multiple choice situation

if (navigator.appName == "Microsoft Internet Explorer " && parseInt (navigator.appVersion.split ( ";") [1]
.replace(/[ ]/g, "").replace("MSIE", "")) < 9) {
return obj.upload(index, file)
}
canvasDataURL(file, function (blob) {
var aafile = new File([blob], file.name, {
type: file.type
})
var isLt1M;
if (file.size < aafile.size) {
isLt1M = file.size
} else {
isLt1M = aafile.size
}

if (isLt1M / 1024 / 1024 > 2) {
return layer.alert('上传图片过大!')
} else {
if (file.size < aafile.size) {
return obj.upload(index, file)
}
obj.upload(index, aafile)
}
})
},
done: function (res) {
//上传完毕回调
},
error: function () {
//请求异常回调
}
});
});

function canvasDataURL(file, callback) { //压缩转化为base64
var reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = function (e) {
const img = new Image()
const quality = 0.8 // 图像质量
const canvas = document.createElement('canvas')
const drawer = canvas.getContext('2d')
img.src = this.result
img.onload = function () {
canvas.width = img.width
canvas.height = img.height
drawer.drawImage(img, 0, 0, canvas.width, canvas.height)
convertBase64UrlToBlob(canvas.toDataURL(file.type, quality), callback);
}
}
}

function convertBase64UrlToBlob (urlData, callback) { // file format into the base64
const urlData.split ARR = ( ',')
const = MIME ARR [0] .match (/: (*); /.?) [. 1]
atoB BSTR = const (ARR [. 1])
the let n-bstr.length =
const = u8arr new new Uint8Array (n-)
the while (N--) {
u8arr [n-] = bstr.charCodeAt (n-)
}
the callback (new new Blob ([u8arr ], {
type: MIME
}));
}

</ Script>
 

Guess you like

Origin www.cnblogs.com/imPedro/p/11297755.html