首页 > 其他分享 >ajax 上传文件

ajax 上传文件

时间:2022-09-24 17:34:35浏览次数:63  
标签:tmp 文件 setAttribute xhr ajax file progress input 上传

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      html,
      body {
        height: 100vh;
        width: 100vw;
      }

      body {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
      }

      body div {
        margin-top: 20px;
      }

      #uploadUrl {
        width: 400px;
        padding: 20px;
        margin-bottom: 30px;
        font-size: 14px;
      }

      img {
        height: 100px;
        width: 100px;
      }
    </style>
  </head>
  <body>
    <!-- accept=".zip" 限制上传类型 -->
    <!-- http://60.205.223.186:8080/jeeplus-vue/api/system/webupload -->
    <input
      type="text"
      id="uploadUrl"
      value="http://192.168.31.203:8082/api/tool/fileUpLoad"
    />
    <input
      id="file"
      onchange="startUpload()"
      type="file"
      name="upload"
      multiple="multiple"
    />
    <div id="pro">0%</div>
    <div id="result">http://www.baidu.com</div>
    <img src="" alt="暂无图片" id="img" />
    <script>
      function startUpload() {
        upload(uploadUrl.value, file, (progress) => {
          pro.innerText =
            ((progress.loaded / progress.total) * 100).toFixed(2) + '%'
        })
          .then((res) => {
          
            // 'http://60.205.223.186:8080/jeeplus-vue' +
            let tmp = JSON.parse(res).url
            result.innerText = tmp
            if (tmp.endsWith('.jpg')) img.src = tmp
            clearUpload()
          })
          .catch((res) => {
            console.log(res,'catch')
            clearUpload()
          })
      }

      function clearUpload() {
        document
          .getElementById('file')
          .parentNode.removeChild(document.getElementById('file'))

        let input = document.createElement('input')
        input.setAttribute('type', 'file')
        input.setAttribute('id', 'file')
        input.setAttribute('name', 'file')
        input.setAttribute('multiple', 'multiple')
        input.setAttribute('onchange', 'startUpload()')

        uploadUrl.parentNode.insertBefore(input, pro)
      }

      function upload(url, file, uploadProgress) {
        return new Promise((resolve, reject) => {
          let xhr = new XMLHttpRequest()
          xhr.open('POST', url, true)
          //xhr.setRequestHeader("Content-Type","multipart/form-data;")//提交文件的时候不需要设置请求头,由浏览器添加相应标识,否则会报错!!!
          var fd = new FormData()
          
          for (let i = 0, len = file.files.length; i < len; i++) {
            fd.append('file', file.files[i])
            fd.append('name', file.files[i].name)
          }
          
          xhr.upload.addEventListener('progress', uploadProgress, false)
          xhr.onreadystatechange = () => {
            if (xhr.readyState == 4 && xhr.status == 200) {
              resolve(xhr.responseText)
            } else if (xhr.readyState == 4 && xhr.status != 200) reject()
          }
            
            xhr.send(fd)
        })
      }
    </script>
  </body>
</html>

 

标签:tmp,文件,setAttribute,xhr,ajax,file,progress,input,上传
From: https://www.cnblogs.com/laremehpe/p/16726044.html

相关文章