feat: 添加文件上传进度跟踪功能,支持实时显示上传速度和剩余时间

This commit is contained in:
Yakumo Hokori
2025-12-11 23:12:45 +08:00
parent ab635e19eb
commit 0c69355c5a
11 changed files with 815 additions and 15 deletions

View File

@@ -3,7 +3,7 @@ mod update;
use clap::Parser;
use login::login_and_get_token;
use update::upload_file;
use update::{upload_file_with_progress, UploadProgress};
use std::process;
#[derive(Parser)]
@@ -25,7 +25,8 @@ struct Cli {
/// Password for authentication
#[arg(short, long)]
password: Option<String>,
}
}
#[tokio::main]
async fn main() {
@@ -63,21 +64,64 @@ async fn main() {
};
println!("正在上传文件: {} 到远程路径: {}", cli.file, cli.remote_path);
println!("进度条说明: [进度百分比] | 上传速度 | 已用时间 | 剩余时间 | 已上传/总大小");
println!();
// 上传文件
match upload_file(token, &cli.file, &cli.remote_path).await {
Ok((true, response)) => {
println!("✅ 文件上传成功!");
println!("服务器响应: {}", response);
}
Ok((false, response)) => {
println!("❌ 文件上传失败!");
println!("服务器响应: {}", response);
process::exit(1);
// 默认使用进度跟踪的上传
match upload_file_with_progress(token, &cli.file, &cli.remote_path, |progress| {
print_progress(&progress);
}).await {
Ok(response) => {
println!("\n✅ 文件上传成功!");
println!("服务器响应: {}", response.text);
}
Err(e) => {
eprintln!("上传过程中发生错误: {}", e);
eprintln!("\n上传过程中发生错误: {}", e);
process::exit(1);
}
}
}
// 显示进度的函数
fn print_progress(progress: &UploadProgress) {
print!("\r\x1b[K"); // 清除从光标到行尾的内容
print!("[");
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))
}
}