1.要求
要求把标签的上传文件功能实现,
接口地址是:https://hmajax.itheima.net/api/uploadimg
2.思路
- 1.获取文件对象
- 2.使用FormData对象携带图片文件
- 3.提交表单数据到服务器
- 4.获取成功回调实现图片回显
3.业务实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="file" class="upload">
<!-- <img src="" alt=""> -->
</body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
//实现上传图片的功能
// 1.获取文件对象
const upload = document.querySelector('.upload');
// 监听文件变化事件
upload.addEventListener('change', function (e) {
//target中的files属性是一个FileList对象(伪数组),包含了用户选择的文件列表
// console.log(e.target.files[0]);//0:File {name: 'JSAPI2.png', lastModified: 1751373447138
const file = e.target.files[0];
//2.使用FormData携带图片文件
const fd = new FormData();//创建一个FormData对象,用于存储要发送到服务器的内容。
fd.append('img', file); //这里的'file'要和后端接收的字段名一致
//3.提交表单数据到服务器,使用图片url网址
axios({
method: 'post',
url: 'https://hmajax.itheima.net/api/uploadimg', // 这里要和后端接口一致
data: fd,
}).then(res => {//图片回显
const img = document.createElement('img');
document.body.appendChild(img);
img.src = res.data.data.url;
console.log(res);
});
});
</script>
</html>


4.设置网页背景图片
axios({
method: "post",
url: 'https://hmajax.itheima.net/api/uploadimg', // 这里要和后端接口一致
data: fd,
}).then(res => {
localStorage.setItem('bg', res.data.data.url)
})
......
const bg = localStorage.getItem('bg')
if (bg) {
document.body.style.backgroundImage = `url(${bg})`
}


被折叠的 条评论
为什么被折叠?



