rust使用curl下载文件并打印下载进度

180it 2023-03-08 PM 497℃ 0条

增加依赖:easy="*"

use curl::easy::Easy;
use std::fs::File;
use std::io::Write;

fn main() {
    let source_url = "https://pic.3gbizhi.com/2019/0927/20190927085959737.jpeg";
    let collect:Vec<&str>    = source_url.split("/").collect();
    let file_path   = collect[collect.len()-1];
    let mut curl =  Easy::new();
    let mut out_file = File::create(file_path).unwrap();
    curl.url(source_url).unwrap();
    curl.progress(true).unwrap();
    curl.progress_function(|total_download_bytes,cur_download_bytes,_total_upload_bytes,_cur_upload_bytes|{
        if total_download_bytes>0.0{
            println!("已下载:{}%",cur_download_bytes/total_download_bytes*100.0);
        }
        else{
            println!("已下载:0%");
        }
        true
    }).unwrap();
    curl.write_function(move |data| {
        out_file.write(&data).unwrap();
        Ok(data.len())
    }).unwrap();
    curl.perform().unwrap();
}

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

rust使用curl下载文件并打印下载进度