修改头像,存入后台
html
<div class="update-avatar"> <img class="avatar" src="../images/5.jpg" alt=""> <div class="avatar-btn"> <span id="pic">修改头像</span> <input id="upload" name="file" accept="image/*" type="file"> </div> </div>
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格式的数据,后端才能读取文件信息,然后由后端把图片存在后台返回文件名,在前端获取并显示就好

源代码:https://github.com/ouxiaojie18/-/tree/master/%E5%A4%B4%E5%83%8F%E4%B8%8A%E4%BC%A0

浙公网安备 33010602011771号