Kirby
首页
文章
随笔书签提示词AI 助手

图片上传和本地存储调用

2024-07-08·
次浏览

AI 摘要

生成中...
index.html
123456
<body>
  <div class="right">
    <label for="bg">更换背景</label>
    <input class="bg-ipt" type="file" id="bg" />
  </div>
</body>
index.js
123456789101112131415161718192021
document.querySelector('.bg-ipt').addEventListener('change', (e) => {
  // 1.选择图片上传,设置body背景
  //console.log(e.target.files[0]);
  const fd = new FormData()
  fd.append('img', e.target.files[0])
  axios({
    url: 'http://hmajax.itheima.net/api/uploadimg',
    method: 'POST',
    data: fd,
  }).then((res) => {
    console.log(res.data)
    const imgUrl = res.data.data.url
    document.body.style.backgroundImage = `url("${imgUrl}")`
    // 2.图片上传成功时,保存图片URL网址到本地
    localStorage.setItem('bgImg', imgUrl)
  })
})
// 3.网页运行后,从本地获取图片的URL网址使用
const bgUrl = localStorage.getItem('bgImg')
// 本地有背景图的地址才设置
bgUrl && (document.body.style.backgroundImage = `url("${bgUrl}")`)

上一篇简易Axios函数的封装post,
下一篇记录视频的上一次播放位置post,