ajax 上傳文件,監聽進度(progress)


mdn

前端代碼 github

<body class="m-2">
  <label for="a" class="btn btn-primary">點擊上傳</label>
  <input id='a' name="file" type="file" accept="image/png, image/jpeg, video/*" style="display:none;" multiple='multiple'>
  <script>
    async function main() {

      const l = console.log
      let fileEle = document.querySelector('#a')
      fileEle.onchange = e => {
        let files = fileEle.files
        if(files.length === 0) return false;

        let data = new FormData()
        for(const file of files){
          data.append('files', file)
        }

        let xhr = new XMLHttpRequest()
        
        xhr.upload.addEventListener('progress', e => {
          if (e.lengthComputable) {
            var percentage = Math.round((e.loaded * 100) / e.total);
            l(`${percentage}%`)
          }
        })

        xhr.open('post', 'http://localhost:5000/upload')
        xhr.responseType = 'json'
        xhr.send(data)

        xhr.upload.addEventListener('loadstart', e => {
          l('上傳開始')
        })
        
        xhr.upload.addEventListener('error', e => {
          l('上傳失敗')
        })

        xhr.upload.addEventListener('abort', e => {
          l('上傳終止')
        })

        xhr.upload.addEventListener('timeout', e => {
          l('由於預設時間到期,上傳終止')
        })

        xhr.upload.addEventListener('load', e => {
          l('上傳成功了')
        })

        xhr.upload.addEventListener('loadend', e => {
          l('上傳已經停止了')
        })

        xhr.onload = () => {
          l(...xhr.response.imgsSrc);
        }

      }
    }
    main();
  </script>
</body>

</html>

后台代碼片段

  @Post('upload')
  @UseInterceptors(FilesInterceptor('files'))
  uploadfile(@UploadedFiles() files, @Body() body) {

    if (!files || files.length === 0) {
      throw new HttpException('參數錯誤', HttpStatus.FORBIDDEN)
    }

    let imagesSrc = []
    for (const file of files) {
      const imgName = `${Date.now()}-${file.originalname}`
      const writeImage = createWriteStream(join(__dirname, '..', 'upload', imgName))
      writeImage.write(file.buffer)
      imagesSrc.push( `http://localhost:5000/images/${imgName}` )
    }
    return {
      imgsSrc: imagesSrc
    }
  }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM