操作步骤很简单,需要会使用HTML,CSS,JS以及Axios和后端提供的URL接口
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.my-img{
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<input type="file" class="upload">
我的头像<img src="" alt="" class="my-img">
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.2.0/axios.min.js"></script>
<script>
// 给文件选择元素绑定选择事件
document.querySelector('.upload').addEventListener('change',e=>{
// 文件选择元素
// 原生代码 e.target.files
// 使用FormData携带图片文件
console.log(e.target.files[0]);
const td = new FormData()
td.append('img',e.target.files[0])
console.log(td);
axios({
url:'http://hmajax.itheima.net/api/uploadimg',
method:'POST',
data:td
}).then(result=>{
console.log(result);
const imgUrl = result.data.data.url
document.querySelector('.my-img').src = imgUrl
})
})
</script>
</html>
标签:files,Axios,console,log,img,data,前端,td,上传
From: https://blog.csdn.net/jk0025/article/details/139574800