playlist_cover_update.html 2.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>歌单封面上传</title>
  </head>
  <body>
      
    <input id="file" type="file" name="filename" />
    <img id="avatar" style="height: 200px; width: 200px; border-radius: 50%;" />
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.20.0-0/axios.min.js
    "></script>
    <script>
      const phone = ''
      const password = ''
      const playlist_id = ''
      const port = 3000
      let cookieToken = ''
      if (!phone || !password) {
        const msg = '请设置你的手机号码和密码'
        alert(msg)
        throw new Error(msg)
      }
      if (!playlist_id) {
        const msg = '请设置你的歌单id'
        alert(msg)
        throw new Error(msg)
      }

      main()
      login()
      async function main() {
        document.querySelector('input[type="file"]').addEventListener(
          'change',
          function (e) {
            var file = this.files[0]
            upload(file)
          },
          false
        )
        const res = await axios({
          url: `http://localhost:${port}/playlist/detail?id=${playlist_id}`,
        })
        document.querySelector('#avatar').src = res.data.playlist.coverImgUrl
      }
      async function login() {
        const res = await axios({
          url: `http://localhost:${port}/login/cellphone?phone=${phone}&password=${password}`,
          withCredentials: true, //关键
        })
        cookieToken = res.data.cookie
      }
      async function upload(file) {
        var formData = new FormData()
        formData.append('imgFile', file)
        const imgSize = await getImgSize(file)
        const res = await axios({
          method: 'post',
          url: `http://localhost:3000/playlist/cover/update?id=${playlist_id}&cookie=${cookieToken}&imgSize=${imgSize.width}&imgX=0&imgY=0`,
          headers: {
            'Content-Type': 'multipart/form-data',
          },
          data: formData,
        })
        document.querySelector('#avatar').src = res.data.data.url
      }
      function getImgSize(file) {
        return new Promise((resolve, reject) => {
          let reader = new FileReader()
          reader.readAsDataURL(file)
          reader.onload = function (theFile) {
            let image = new Image()
            image.src = theFile.target.result
            image.onload = function () {
              resolve({
                width: this.width,
                height: this.height,
              })
            }
          }
        })
      }
    </script>
  </body>
</html>