文章转自:http://blog.csdn.net/javarat/article/details/8002198
本节jwisp为大家举例说明如果使用上节介绍的函数和参数,在使用libcurl的过程中,如何获取下载目标文件的大小 ,下载进度条,断点续传等,这些基本的函数,将为jwisp在最后处理下载过程异常中断等问题提供支持.
1. 编写得到下载目标文件的大小的函数
- long getDownloadFileLenth(const char *url){
- long downloadFileLenth = 0;
- CURL *handle = curl_easy_init();
- curl_easy_setopt(handle, CURLOPT_URL, url);
- curl_easy_setopt(handle, CURLOPT_HEADER, 1); //只需要header头
- curl_easy_setopt(handle, CURLOPT_NOBODY, 1); //不需要body
- if (curl_easy_perform(handle) == CURLE_OK) {
- curl_easy_getinfo(handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &downloadFileLenth);
- } else {
- downloadFileLenth = -1;
- }
- return downloadFileLenth;
- }
2. 下载中回调自己写的得到下载进度值的函数
下载回调函数的原型应该为:
- int progressFunc(const char* flag, double dtotal, double dnow, double ultotal, double ulnow);
a. 应该在外部声明一个远程下载文件大小的全局变量
- double downloadFileLenth = 0;
为了断点续传, 还应该声明一个本地文件大小的全局变量
- double localFileLenth = 0;
b. 编写一个得到进度值的函数getProgressValue()
- int getProgressValue(const char* flag, double dt, double dn, double ult, double uln){
- double showTotal, showNow;
- if (downloadFileLenth == 0){
- downloadFileLenth = getDownloadFileLenth(url);
- }
- showTotal = downloadFileLenth;
- if (localFileLenth == 0){
- localFileLenth = getLocalFileLenth(filePath);
- }
- showNow = localFileLenth + dn;
- //然后就可以调用你自己的进度显示函数了, 这里假设已经有一个进度函数, 那么只需要传递当前下载值和总下载值即可.
- showProgressValue(showNow, showTotal);
- }
c. 在下载中进行三个下载参数的设置
- curl_easy_setopt(handle, CURLOPT_NOPROGRESS, 0);
- curl_easy_setopt(handle, CURLOPT_PROGRESSFUNCTION, getProgressValue); //设置回调的进度函数
- curl_easy_setopt(handle, CURLOPT_PROGRESSDATA, “flag”); //此设置对应上面的const char *flag
3. 断点续传
用libcurl实现断点续传很简单,只用两步即可实现,一是要得到本地文件已下载的大小,通过函数getLocalFileLenth()方法来得到,二是设置CURLOPT_RESUME_FROM_LARGE参数的值为已下载本地文件大小.
得到本地文件大小的函数:
- long getLocalFileLenth(const char* localPath);
设置下载点如下即可:
- curl_easy_setopt(handle, CURLOPT_RESUME_FROM_LARGE, getLocalFileLenth(localFile));