html
修改头像
css
.avatar-btn { display: inline-block; position: relative; vertical-align: top; cursor: pointer; width: 100px; height: 20px; } .avatar-btn input { display: none; } .avatar-btn span { line-height: 100px; } .avatar { border-radius: 100%; height: 100px; width: 100px; margin-right: 30px; }
js
$("#pic").click(function () { $("#upload").click(); //隐藏了input:file样式后,点击头像就可以本地上传 $("#upload").on("change", function () { let file = this.files[0]; var formData = new FormData(); formData.append("file", file); $.ajax({ url: "https://kaopeixia.com/webapi/file/getfilepath",//因为后端设置权限了,这里这个链接访问不了,换成你们自己的后端链接就好 type: "POST", data: formData, cache: false, processData: false, contentType: false, dataType: "json", xhrFields: { withCredentials: true }, success: function (result) { if (result.status == 201) { $(".avatar").attr( "src", "https://kaopeixia.com/webapi/" + result.filename ); } } }); }); });
获取的file[0]需要把它存成formData格式的数据,后端才能读取文件信息,然后由后端把图片存在后台返回文件名,在前端获取并显示就好
源代码: