使用XMLHttpRequest上传视频

先触发input的change事件

// input的change事件
  handleFileChange = (e) => {
    const file = e.target.files[0]
    // 限制视频大小格式等
    if (file.size > 500 * 1024 * 1024) {
      message.error('视频不能大于500M')
      return
    }
    if (file.type && !file.type.includes('mp4')) {
      message.error('请上传mp4格式的视频')
      return
    }
    this.handleUploadVideo(file)
  }

如果需要展示进度条的话使用XMLHttpRequest

handleUploadVideo = (file) => {
	var xhr = new XMLHttpRequest()
	xhr.onreadystatechange = () => {
	  if (xhr.readyState === 4 && xhr.status === 200) {
	    console.log('===上传成功===', xhr)
	  }
	  if (xhr.readyState === 4 && xhr.status === 0) {
	    console.log('===上传失败===', xhr.status)
	  }
	}
	
	xhr.upload.addEventListener('progress', (event) => {
		// 监听上传进度大约每200ms触发一次
	  if (event.lengthComputable) {
	    console.log('===🚀===>', Math.ceil(event.loaded * 100 / event.total) + '%')
	  }
	}, false)
	/*
	 * setRequestHeader放在open后send前
	 **/
	// open('',上传地址)
	xhr.open('PUT', uploadUrl)
	// 添加请求头
	xhr.setRequestHeader('Content-Type', 'video/mp4')
	xhr.send(file)
}

不需要展示进度条的话可以使用fetch

handleUploadVideo = (file) => {
	//fetch(上传视频的链接,{})
	fetch(uploadUrl, {
	    method: 'put', 
	       body: file
	     }).then(res => {
	       if (res.status === 200) {
	        console.log('===上传成功===')
	       }
	     })
}

方法详情:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值