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>

1053296-20180910000605680-1609939613.png

后台代码片段

  @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
    }
  }

转载于:https://www.cnblogs.com/ajanuw/p/9616098.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值