大橙子网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

libcurl第八课下载Http或FTP图片

场景一 保存成图片
代码
 static size_t WriteFile(void *ptr, size_t size, size_t nmemb, void *stream)
 {
  std::ofstream* ofs = (std::ofstream*)stream;
  size_t nLen = size * nmemb;
  ofs->write((char*)ptr, nLen);
  return nLen;
 }
 static void TestStorePhotoFileFromUrl()
 {
  std::ofstream ofs;
  ofs.open("aa3ab705-a7d5-4892-b63d-2ccdb54db9a21561977015816.jpg", std::ios::out | std::ios::binary);
  std::string strUrl = "ftp://192.168.11.161:9010/successImage/aa3ab705-a7d5-4892-b63d-2ccdb54db9a21561977015816.jpg";
  std::string strPhotoBuffer;
  CURL *pCurlHandle;
  pCurlHandle = curl_easy_init();
  curl_easy_setopt(pCurlHandle, CURLOPT_URL, strUrl.c_str());
  curl_easy_setopt(pCurlHandle, CURLOPT_WRITEDATA, &ofs);
  curl_easy_setopt(pCurlHandle, CURLOPT_WRITEFUNCTION, WriteFile);
  CURLcode nCurlRet = curl_easy_perform(pCurlHandle);
  if ((nCurlRet != CURLE_OK) && (nCurlRet != CURLE_WRITE_ERROR))
  {
   std::cout << "通过LibCurl获取:" << strUrl << "图片失败,错误码是:" << nCurlRet;
  }
  ofs.close();
  curl_easy_cleanup(pCurlHandle);
 }

网站建设哪家好,找成都创新互联!专注于网页设计、网站建设、微信开发、小程序定制开发、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了毕节免费建站欢迎大家使用!

场景二 保存到缓存
代码
 static size_t WriteBuffer(void *ptr, size_t size, size_t nmemb, void *stream)
 {
  std::string* pStrBuffer = (std::string*)stream;
  size_t nLen = size * nmemb;
  pStrBuffer->append((char*)ptr, nLen);
  return nLen;
 }
 static void TestStoreBufferFromUrl()
 {
  std::string strUrl = "ftp://192.168.11.161:9010/successImage/aa3ab705-a7d5-4892-b63d-2ccdb54db9a21561977015816.jpg";
  std::string strPhotoBuffer;
  CURL *pCurlHandle;
  pCurlHandle = curl_easy_init();
  curl_easy_setopt(pCurlHandle, CURLOPT_URL, strUrl.c_str());
  curl_easy_setopt(pCurlHandle, CURLOPT_WRITEDATA, &strPhotoBuffer);
  curl_easy_setopt(pCurlHandle, CURLOPT_WRITEFUNCTION, WriteBuffer);
  CURLcode nCurlRet = curl_easy_perform(pCurlHandle);
  if ((nCurlRet != CURLE_OK) && (nCurlRet != CURLE_WRITE_ERROR))
  {
   std::cout << "通过LibCurl获取:" << strUrl << "图片失败,错误码是:" << nCurlRet;
  }
  else
  {
   std::ofstream ofs;
   ofs.open("aa3ab705-a7d5-4892-b63d-2ccdb54db9a21561977015816.jpg", std::ios::out | std::ios::binary);
   ofs << strPhotoBuffer;
   ofs.close();
  }
  curl_easy_cleanup(pCurlHandle);
 }

注意:
std::ios::binary必须携带,否则图片写文件有丢失


网站栏目:libcurl第八课下载Http或FTP图片
文章路径:http://dzwzjz.com/article/jphggo.html
在线咨询
服务热线
服务热线:028-86922220
TOP