feat: 添加文件上传进度跟踪功能,支持实时显示上传速度和剩余时间
This commit is contained in:
78
examples/progress_demo.rs
Normal file
78
examples/progress_demo.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
use upfs::update::{upload_file_with_progress, UploadProgress};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("🔥 上传进度跟踪演示");
|
||||
println!("================");
|
||||
|
||||
// 模拟登录获取token (这里使用一个假的token)
|
||||
let token = "Bearer fake-token-for-demo".to_string();
|
||||
let file_path = "test_file.txt";
|
||||
let remote_path = "/demo/progress_test.txt";
|
||||
|
||||
// 设置进度回调函数
|
||||
let progress_callback = |progress: UploadProgress| {
|
||||
print_progress(&progress);
|
||||
};
|
||||
|
||||
println!("开始上传: {} -> {}", file_path, remote_path);
|
||||
println!("进度条说明: [进度百分比] | 上传速度 | 已用时间 | 剩余时间 | 已上传/总大小");
|
||||
println!();
|
||||
|
||||
// 上传文件并显示进度
|
||||
match upload_file_with_progress(token, file_path, remote_path, progress_callback).await {
|
||||
Ok(response) => {
|
||||
println!("\n✅ 上传完成!");
|
||||
println!("服务器状态: {}", response.status);
|
||||
println!("服务器响应: {}", response.text);
|
||||
}
|
||||
Err(e) => {
|
||||
println!("\n❌ 上传失败: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 显示进度的函数
|
||||
fn print_progress(progress: &UploadProgress) {
|
||||
print!("\r[");
|
||||
|
||||
let bar_width = 30;
|
||||
let filled = (progress.percentage / 100.0 * bar_width as f64) as usize;
|
||||
for i in 0..bar_width {
|
||||
if i < filled {
|
||||
print!("=");
|
||||
} else if i == filled {
|
||||
print!(">");
|
||||
} else {
|
||||
print!(" ");
|
||||
}
|
||||
}
|
||||
|
||||
print!("] {:.1}% | {} | {} | {}",
|
||||
progress.percentage,
|
||||
progress.format_speed(),
|
||||
progress.format_elapsed_time(),
|
||||
progress.format_remaining_time()
|
||||
);
|
||||
|
||||
print!(" | {}/{}",
|
||||
format_bytes(progress.bytes_uploaded),
|
||||
progress.format_bytes()
|
||||
);
|
||||
|
||||
std::io::Write::flush(&mut std::io::stdout()).unwrap();
|
||||
}
|
||||
|
||||
fn format_bytes(bytes: u64) -> String {
|
||||
if bytes < 1024 {
|
||||
format!("{} B", bytes)
|
||||
} else if bytes < 1024 * 1024 {
|
||||
format!("{:.2} KB", bytes as f64 / 1024.0)
|
||||
} else if bytes < 1024 * 1024 * 1024 {
|
||||
format!("{:.2} MB", bytes as f64 / (1024.0 * 1024.0))
|
||||
} else {
|
||||
format!("{:.2} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user