<div class="layui-upload upload"> <button type="button" class="layui-form-label" id="upload">上传图片</button> <input class="layui-upload-file" type="file" accept="" name="file"> <div class="layui-upload-list"> <img class="layui-upload-img" id="demo1" οnlοad="AutoResizeImage(300,300,this)"> <p id="demoText"></p> </div> </div>
function upload(){
layui.use(['laypage', 'layer', 'upload'], function () {
var laypage = layui.laypage //设置配置环境
, layer = layui.layer
, upload = layui.upload
//上传图片
var uploadInst = upload.render({
elem: '#upload'
, url: Domain.webUrl + "/api/" + AppConfig.version + "/file/img/upload" //改成您自己的上传接口
,
data:{"fileName":"111"}
, before: function (obj) {
//预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$('#demo1').attr('src', result); //图片链接(base64)
});
}
, done: function (res) {
alert(res.message)
imgs.push(res.message)
//上传成功
}
, error: function () {
//演示失败状态,并实现重传
var demoText = $('#demoText');
demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
demoText.find('.demo-reload').on('click', function () {
uploadInst.upload();
});
}
});
});
}
控制图片大小
function AutoResizeImage(maxWidth, maxHeight, objImg) {
var img = new Image();
img.src = objImg.src;
var hRatio;
var wRatio;
var Ratio = 1;
var w = img.width;
var h = img.height;
wRatio = maxWidth / w;
hRatio = maxHeight / h;
if (maxWidth == 0 && maxHeight == 0) {
Ratio = 1;
} else if (maxWidth == 0) { //
if (hRatio < 1) Ratio = hRatio;
} else if (maxHeight == 0) {
if (wRatio < 1) Ratio = wRatio;
} else if (wRatio < 1 || hRatio < 1) {
Ratio = (wRatio <= hRatio ? wRatio : hRatio);
}
if (Ratio < 1) {
w = w * Ratio;
h = h * Ratio;
}
objImg.height = h;
objImg.width = w;
}