Files
upfs/examples/basic_usage.rs

78 lines
2.4 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 这个示例展示了如何使用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))
}
}