jq替换用户头像(选择一张图片)

html:
<div class="mui-table-view info_header">
头像
<img src="<php>
$info['head'] = $info['head'] ? '/upload/'.$info['head'] : '__TMPL__/public/style/images/head4.jpg';
echo $info['head'];
</php>" url="{$info['head']}" class="headImg" id="uphead">
<a class="mui-navigate-right"><input type="file" class="upfile" accept="*/*"></a>
</div>
<button class="mui-btn mui-btn-outlined info_save">保存</button>

j
s:选择图片
$(function () {
$('.info_header').each(function () {
var $this = $(this),
btn = $this.find('.upfile'),
img = $this.find('img');
btn.on('change', function () {
var file = $(this)[0].files[0],// 一张图片
imgSrc = $(this)[0].value,
url = URL.createObjectURL(file);
if (!/.(jpg|jpeg|png|JPG|PNG|JPEG)$/.test(imgSrc)) {
layer.msg("请上传jpg或png格式的图片!");
return false;
} else {
img.attr('src', url);
img.css({'opacity': '1'});
}
});
});
})
拿到的是blob类型的图片,将其转换为base64,并通过ajax提交给后台
$(".info_save").click(function () {
var data = {};
var list = [];
data.position_name = $("input[name='position_name']").val();
data.work = $("input[name='work']").val();
data.job = $("input[name='job']").val();
data.society_job = $("input[name='society_job']").val();
data.address = $("input[name='address']").val();
data.group_id = $('.select_id').text();
// blob类型转换为base64类型
fetch($('#uphead').attr("src")).then(data=>{
const blob = data.blob();
return blob;
}).then(blob=>{
let reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
$('#uphead').attr("src",reader.result)
list.push(reader.result);
data.input_file = list;
console.log('参数', data)
var url = "/home/profile/edit"; // 请求地址
$.ajax({
url: url,
type: "post",
dataType: "json",
data: data,
success: function (re) {
console.log('结果', re);
if (re.code == 1) {
layer.msg('保存成功!');
window.location.href = re.url;
} else {
layer.msg('信息未做改动');
}
},

});
};
});
});
原文地址:https://www.cnblogs.com/LindaBlog/p/12925024.html