使用libcurl实现获取目标文件大小, 下载进度显示, 断点续传等功能

文章转自:http://blog.csdn.net/javarat/article/details/8002198 

本节jwisp为大家举例说明如果使用上节介绍的函数和参数,在使用libcurl的过程中,如何获取下载目标文件的大小 ,下载进度条,断点续传等,这些基本的函数,将为jwisp在最后处理下载过程异常中断等问题提供支持.

1.      编写得到下载目标文件的大小的函数

[cpp]  view plain copy
  1. long getDownloadFileLenth(const char *url){  
  2.     long downloadFileLenth = 0;  
  3.     CURL *handle = curl_easy_init();  
  4.     curl_easy_setopt(handle, CURLOPT_URL, url);  
  5.     curl_easy_setopt(handle, CURLOPT_HEADER, 1);    //只需要header头  
  6.     curl_easy_setopt(handle, CURLOPT_NOBODY, 1);    //不需要body  
  7.     if (curl_easy_perform(handle) == CURLE_OK) {  
  8.         curl_easy_getinfo(handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &downloadFileLenth);  
  9.     } else {  
  10.         downloadFileLenth = -1;  
  11.     }  
  12.     return downloadFileLenth;  
  13. }  

2.      下载中回调自己写的得到下载进度值的函数

下载回调函数的原型应该为:

[cpp]  view plain copy
  1. int progressFunc(const char* flag, double dtotal, double dnow, double ultotal, double ulnow);  


a.      应该在外部声明一个远程下载文件大小的全局变量

[cpp]  view plain copy
  1. double downloadFileLenth = 0;  


为了断点续传还应该声明一个本地文件大小的全局变量

[cpp]  view plain copy
  1. double localFileLenth = 0;  


b.      编写一个得到进度值的函数getProgressValue()

[cpp]  view plain copy
  1. int getProgressValue(const char* flag, double dt, double dn, double ult, double uln){  
  2.     double showTotal, showNow;  
  3.     if (downloadFileLenth == 0){  
  4.         downloadFileLenth = getDownloadFileLenth(url);  
  5.     }  
  6.     showTotal = downloadFileLenth;  
  7.     if (localFileLenth == 0){  
  8.         localFileLenth = getLocalFileLenth(filePath);  
  9.     }  
  10.     showNow = localFileLenth + dn;  
  11.     //然后就可以调用你自己的进度显示函数了, 这里假设已经有一个进度函数, 那么只需要传递当前下载值和总下载值即可.  
  12.     showProgressValue(showNow, showTotal);  
  13. }  

c.       在下载中进行三个下载参数的设置

[cpp]  view plain copy
  1. curl_easy_setopt(handle, CURLOPT_NOPROGRESS, 0);  
  2.   
  3. curl_easy_setopt(handle, CURLOPT_PROGRESSFUNCTION, getProgressValue);  //设置回调的进度函数  
  4.   
  5. curl_easy_setopt(handle, CURLOPT_PROGRESSDATA, “flag”);   //此设置对应上面的const char *flag  


3.      断点续传

libcurl实现断点续传很简单,只用两步即可实现,一是要得到本地文件已下载的大小,通过函数getLocalFileLenth()方法来得到,二是设置CURLOPT_RESUME_FROM_LARGE参数的值为已下载本地文件大小.

得到本地文件大小的函数:

[cpp]  view plain copy
  1. long getLocalFileLenth(const char* localPath);  


设置下载点如下即可:

                    

[cpp]  view plain copy
  1. curl_easy_setopt(handle, CURLOPT_RESUME_FROM_LARGE, getLocalFileLenth(localFile));        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值