feat: 添加文件上传进度跟踪功能,支持实时显示上传速度和剩余时间
This commit is contained in:
78
examples/basic_usage.rs
Normal file
78
examples/basic_usage.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
// 这个示例展示了如何使用UPFS库的基本功能
|
||||
// 包括上传文件和进度跟踪
|
||||
|
||||
// 由于示例是独立的,我们需要通过cargo run --example来运行
|
||||
// 这会自动链接到库
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("UPFS 基本使用示例");
|
||||
println!("=================");
|
||||
|
||||
// 创建一个测试文件
|
||||
std::fs::write("test_upload.txt", "这是一个测试文件\n用于演示上传功能")?;
|
||||
|
||||
// 模拟token(实际使用中需要通过登录获取)
|
||||
let token = "Bearer test-token".to_string();
|
||||
let file_path = "test_upload.txt";
|
||||
let remote_path = "/demo/test.txt";
|
||||
|
||||
println!("准备上传文件: {}", file_path);
|
||||
println!("远程路径: {}", remote_path);
|
||||
println!();
|
||||
|
||||
// 演示1: 使用进度回调上传
|
||||
println!("演示1: 带进度跟踪的上传");
|
||||
println!("----------------------------");
|
||||
|
||||
let start_time = std::time::Instant::now();
|
||||
|
||||
// 这里使用简单的进度回调
|
||||
match upfs::update::upload_file_with_progress(
|
||||
token.clone(),
|
||||
file_path,
|
||||
remote_path,
|
||||
|progress| {
|
||||
if progress.percentage <= 100.0 {
|
||||
print!("\r\x1b[K进度: {:.1}% ({}/{}) - {} - {}",
|
||||
progress.percentage,
|
||||
format_bytes(progress.bytes_uploaded),
|
||||
format_bytes(progress.total_bytes),
|
||||
progress.format_speed(),
|
||||
progress.format_remaining_time()
|
||||
);
|
||||
}
|
||||
std::io::Write::flush(&mut std::io::stdout()).unwrap();
|
||||
}
|
||||
).await {
|
||||
Ok(response) => {
|
||||
println!("\n✅ 上传成功!");
|
||||
println!("状态码: {}", response.status);
|
||||
println!("响应: {}", response.text);
|
||||
println!("总用时: {:?}", start_time.elapsed());
|
||||
}
|
||||
Err(e) => {
|
||||
println!("\n❌ 上传失败: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("演示完成!");
|
||||
|
||||
// 清理测试文件
|
||||
std::fs::remove_file("test_upload.txt").ok();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn format_bytes(bytes: u64) -> String {
|
||||
if bytes < 1024 {
|
||||
format!("{} B", bytes)
|
||||
} else if bytes < 1024 * 1024 {
|
||||
format!("{:.1} KB", bytes as f64 / 1024.0)
|
||||
} else if bytes < 1024 * 1024 * 1024 {
|
||||
format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
|
||||
} else {
|
||||
format!("{:.1} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user