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>
js:选择图片
$(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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」