<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片上传</title>
</head>
<body>
<!-- 文件选择元素 -->
<input type="file" class="upload">
<img src="" alt="" class="img">
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
/**
* 目标:图片上传,显示到网页上
* 1. 获取图片文件
* 2. 使用 FormData 携带图片文件
* 3. 提交到服务器,获取图片url网址使用
*/
document.querySelector('.upload').addEventListener('change', function (e) {
const imgfile = e.target.files[0];
console.log(imgfile);
const formData = new FormData();
formData.append('img', imgfile);
axios({
url: "https://hmajax.itheima.net/api/uploadimg",
method: "POST",
data: formData
}).then(res => {
console.log(res);
const imgurl = res.data.data.url
document.querySelector('.img').src = imgurl;
})
})
</script>
</body>
</html>