<div class="info-item business-license">
<label class="info-label">营业执照</label>
<div class="info-input-wrap">
<div class="license-wrap">
<img class="license-img" id="licenseImg" onload="javascript:DrawImage(this,167,198)" src="${staticURL }/image/default-license.png" />
</div>
<div class="license-btn">
<span class="license-text">上传营业执照</span>
<input type="file" class="upload-btn" id="uloadBtn1" name="licenseImgFile" accept=".png,.jpg,.jpeg" />
</div>
<div class="license-remove" id="removeLicense">×</div>
</div>
</div>上传图片后img标签展示出来,并等比例缩放,设置最大宽高为167,198;
编写input上传事件,并显示预览图片。
$('#uloadBtn1').on('change', function () {
var files = this.files[0];
var objUrl = showPhoto(this.files[0]);
if (objUrl) {
$("#licenseImg").attr("src", objUrl);
$('.info-input-wrap').addClass('bicense-wrap')
$(this).parents('.license-btn').addClass('license-change');
}
var formData = new FormData();
formData.append('file', $('#uloadBtn1')[0].files[0]); //添加图片信息的参数
})编写图片预览方法
//头像预览
function showPhoto (file) {
var url = null;
if (window.createObjectURL != undefined) { // basic
url = window.createObjectURL(file);
} else if (window.URL != undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;
}以上实现了选择图片,再页面上预览。再图片加载时,根据图片大小来实现缩放,设置图片显示的大小。使用加载方法。
function DrawImage(ImgObj, maxWidth, maxHeight){
//原图片原始地址(用于获取原图片的真实宽高,当<img>标签指定了宽、高时不受影响)
image.src = ImgObj.src;// 用于设定图片的宽度和高度
var tempWidth;
var tempHeight;
if(image.width > 0 && image.height > 0){
if((image.width/image.height) >= maxWidth / maxHeight){
if(image.width > maxWidth){
empWidth = maxWidth;
tempHeight = (image.height * maxWidth) / image.width;
}else{
tempWidth = image.width;
tempHeight = image.height;
}
}else{
if(image.height>maxHeight){
tempHeight = maxHeight; // 按原图片的比例进行缩放
tempWidth = (image.width * maxHeight) / image.height;
}else{
tempWidth = image.width;
tempHeight = image.height;
}
}
// 设置页面图片的宽和高
ImgObj.height = tempHeight;
ImgObj.width = tempWidth;
}
}因图片加载时调用该方法,DrawImage需要再放在最前。
随时随地看视频