use std::{
    io::{BufReader, Read, Write},
    path::PathBuf,
};

fn main() {
    let mut buf = [0; 1024];
    let response = ureq::get("https://ts1.cn.mm.bing.net/favicon.ico")
        .call()
        .unwrap();

    let content_length = response
        .header("Content-Length")
        .unwrap_or("0")
        .parse::<usize>()
        .unwrap_or(0);

    println!("{}", content_length);

    let mut reader = BufReader::new(response.into_reader());

    let write_path = PathBuf::from("favicon.ico");

    if write_path.is_file() {
        let _ = std::fs::remove_file(&write_path);
    }

    let mut file = std::fs::OpenOptions::new()
        .append(true)
        .create_new(true)
        .open(write_path)
        .unwrap();

    let mut read_length = 0;

    loop {
        let length = reader.read(&mut buf).unwrap();
        file.write_all(&buf[0..length]).unwrap();
        read_length = read_length + length;

        if content_length > 0 && length != 0 {
            let progress = read_length as f64 / content_length as f64;
            println!("{}%", progress * 100.0);
        }

        if length == 0 {
            break;
        }
    }
}
最后修改:2024 年 03 月 02 日
如果觉得我的文章对你有用,请随意赞赏