[JS]前端图片上传

本节目标

掌握图片/文件上传

  • 图片上传
  • 更换背景
  • 个人信息设置

图片上传

步骤

  1. 获取图片文件对象
  2. 使用FormData携带图片文件

3. 提交表单数据到服务器, 得到图片URL地址

流程

示例

<body>
  <!-- 文件选择元素 -->
  <input type="file" class="upload">

  <img src="" alt="" class="my-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 file = e.target.files[0]
      const fd = new FormData()
      fd.append('img', file)
      axios({
        url: 'http://hmajax.itheima.net/api/uploadimg',
        method: 'post',
        data: fd
      }).then(({ data }) => {
        const url = data.data.url
        document.querySelector('.my-img').src = url
      })
    })
  </script>
</body>

个人信息设置

  1. 提交表单
  2. 结果提示
/**
 * 目标1:信息渲染
 *  1.1 获取用户的数据
 *  1.2 回显数据到标签上
 * */
const render = () => {
  axios({
    url: 'http://hmajax.itheima.net/api/settings',
    params: {
      creator: '水壶'
    }
  }).then(({ data }) => {
    const result = data.data
    const keys = Object.keys(result)
    keys.forEach(key => {

      if (key === 'avatar') {
        // 单独处理头像
        document.querySelector('.prew').src = result[key]
      } else if (key === 'gender') {
        // 单独处理性别
        const genderEls = document.querySelectorAll('.gender')
        // 把属性值作为下标, 选中元素, 然后设置状态
        genderEls[result[key]].checked = true

      } else {
        // 处理其他表单项
        document.querySelector(`.user-form .${key}`).value = result[key]
      }

    })

  })
}

render()
/**
 * 目标2:头像修改
 * 2.1 获取文件对象
 * 2.2 提交数据保存
 */
document.querySelector('.upload').addEventListener('change', e => {
  console.log();
  const data = e.target.files[0]
  const fd = new FormData()
  fd.append('avatar', data)
  fd.append('creator', creator)
  axios({
    url: 'http://hmajax.itheima.net/api/avatar',
    method: 'put',
    data: fd,
  }).then(({ data }) => {
    document.querySelector('.prew').src = data.data.avatar
  })
})
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值