chuangte_bike_newxcx/common/qiniuUploadProgress.js

67 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2026-05-25 17:13:15 +08:00
import Vue from 'vue'
export const qiniuUploadProgressState = Vue.observable({
visible: false,
progress: 0,
speedText: '0KB/s',
sizeText: '',
title: '上传中'
})
let lastTime = 0
let lastSent = 0
export function formatFileSize(bytes) {
const n = Number(bytes) || 0
if (n <= 0) return '0B'
if (n < 1024) return n + 'B'
if (n < 1024 * 1024) return (n / 1024).toFixed(1) + 'KB'
return (n / 1024 / 1024).toFixed(2) + 'MB'
}
export function formatSpeed(bytesPerSec) {
const n = Number(bytesPerSec) || 0
if (n <= 0) return '0KB/s'
if (n < 1024) return n.toFixed(0) + 'B/s'
if (n < 1024 * 1024) return (n / 1024).toFixed(1) + 'KB/s'
return (n / 1024 / 1024).toFixed(2) + 'MB/s'
}
export function resetQiniuUploadProgress() {
qiniuUploadProgressState.progress = 0
qiniuUploadProgressState.speedText = '0KB/s'
qiniuUploadProgressState.sizeText = ''
lastTime = 0
lastSent = 0
}
export function showQiniuUploadProgress(title = '上传中') {
resetQiniuUploadProgress()
qiniuUploadProgressState.title = title
qiniuUploadProgressState.visible = true
}
export function hideQiniuUploadProgress() {
qiniuUploadProgressState.visible = false
resetQiniuUploadProgress()
}
export function updateQiniuUploadProgress(res) {
const now = Date.now()
const sent = res.totalBytesSent || 0
const total = res.totalBytesExpectedToSend || 0
qiniuUploadProgressState.progress = Math.min(100, Math.max(0, res.progress || 0))
if (total > 0) {
qiniuUploadProgressState.sizeText = formatFileSize(sent) + ' / ' + formatFileSize(total)
}
if (lastTime && now > lastTime) {
const deltaBytes = sent - lastSent
const deltaTime = (now - lastTime) / 1000
if (deltaTime > 0 && deltaBytes >= 0) {
qiniuUploadProgressState.speedText = formatSpeed(deltaBytes / deltaTime)
}
}
lastTime = now
lastSent = sent
}