Bootstrap5 综合案例 --- 图片上传相关案例
1. 图片上传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片上传</title>
</head>
<body>
<input type="file" class="upload">
<img class="my-img" src="" alt="">
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
// 绑定 change 事件,获取文件对象
const upload = document.querySelector(".upload").addEventListener("change", e => {
// 上传图片必须是 type: multipart/form-data类型的数据
// 所以需要实例化form-data对象来承载图片对象
const fd = new FormData()
fd.append("img", e.target.files[0])
// 发送请求,将图片保存在服务器
axios({
url: "http://hmajax.itheima.net/api/uploadimg",
method: "post",
data: fd
}).then(result => {
document.querySelector(".my-img").src = result.data.data.url
})
})
</script>
</body>
</html>
2. 更换网站背景图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片上传</title>
</head>
<body>
<div>
<label for="bg" style="border: 1px solid gray;padding: 5px 10px;border-radius: 15%;float: right;margin-right: 20px">更换背景</label>
<!-- 隐藏文件选择器,当点击label时就相当于点击了文件选择器 -->
<input type="file" class="bg-ipt" id="bg" style="display: none">
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
// 绑定 change 事件,获取文件对象
const upload = document.querySelector(".bg-ipt").addEventListener("change", e => {
// 上传图片必须是 type: multipart/form-data类型的数据
// 所以需要实例化form-data对象来承载图片对象
const fd = new FormData()
fd.append("img", e.target.files[0])
// 发送请求,将图片保存在服务器
axios({
url: "http://hmajax.itheima.net/api/uploadimg",
method: "post",
data: fd
}).then(result => {
// 将整个body的背景图片换成服务器返回的url
document.body.style.backgroundImage = `url(${result.data.data.url})`
// 将url保存在本地存储中
localStorage.setItem("bg", result.data.data.url)
})
})
const bgUrl = localStorage.getItem("bg")
// 如果bgUrl有值,则执行&&后面的,如果没有值则不执行
bgUrl && (document.body.style.backgroundImage = `url(${bgUrl})`)
</script>
</body>
</html>
python防脱发技巧

浙公网安备 33010602011771号