服务端处理商品文档的图片元素(提供了描述,图片URL信息)时,采用HTTP把文件下载到本地服务器,并把图片信息保存在tb_gdsn_goods_pic表中.
开发时注意:
.从SVN上下载vendor\curl-7.31.0到本地环境
.vs2005环境设置(或者工程属性):
include路径: v:\curl-7.31.0\include
lib路径v:\curl-7.31.0\vs\vc8\lib\Debug
.修改CExtFile,支持在下载前确定文件名
.图片下载参考下面的demo代码
1.CExtFile修改
CExtFile的实现在lssdk工程中,增加了NewFileName方法,用于获取具有唯一性的将要保存在本地的图片文件的名称。
可以从trunk下复制到分支.
增加NewFileName定义.
class LS_API CExtFile {
public:
int NewFileName(char *file_name,const char *suffix); ///< 生成唯一文件名
};
ExtFile.cpp
int CExtFile::NewFileName(char *file_name,const char *suffix) {
if (this->GetTempFile(fn))
return -1;
if (suffix)
ACE_OS::sprintf(file_name,"%s\\%s.%s",root_path_,fn,suffix);
else
ACE_OS::sprintf(file_name,"%s\\%s",root_path_,fn);
return 0;
}
2.demo代码
#include <curl/curl.h>
#include <curl/easy.h>
#pragma comment(lib,"libcurl.lib")
#pragma comment(lib,"wldap32.lib")
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
int http_download_pic(const char *url,const char *outfilename) {
CURL *curl;
FILE *fp;
CURLcode res;
curl = curl_easy_init(); ///< @todo 在插件初始化(Initialize)时执行(应该是只需要执行一次)
if (curl) {
fp = fopen(outfilename,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl); ///< @todo 插件释放(Release)时执行
fclose(fp);
if (res!=CURLE_OK)
return -1;
}
return 0;
}
int handle_pic_element() {
///< @todo 解析ULR后缀(如jpg)
char file_ext[MAX_PATH];
///< 确定文件名
char pic_file_name[MAX_PATH];
CExtFileControl pic_file_control_;
pic_file_control_.NewFileName(pic_file_name,file_ext); ///< 保存的文件和原文件有相同的扩展名
if (http_download_pic(url,pic_file_name))
return -1;
///< @todo 把商品图片的文件名称信息写入tb_gdsn_goods_pic表中
return 0;
}
3.资料
Download file using libcurl in C/C++
http://stackoverflow.com/questions/1636333/download-file-using-libcurl-in-c-c
demo工程在连接libcurl.lib时报以下错误:
error LNK2019: unresolved external symbol __imp__curl_easy_init referenced i
解决方法:
Project properties -> all releases -> configuration properties -> linker -> input -> and set
additional dependencies to = libcurl.lib ws2_32.lib winmm.lib wldap32.lib
Add new macros at the preprocessors = ;BUILDING_LIBCURL;HTTP_ONLY