C++ libcurl upload file / 使用 libcurl 做檔案上傳

整理一下留著以後應該還是會用到

#include <stdio.h>
#include <iostream>
#include <string>
#define CURL_STATICLIB
#include "curl/curl.h"

size_t write_console(void *buffer, size_t size, size_t count, void *userp) {
  std::string str((const char*)buffer, size*count);
  std::cout<<str;
  return count*size;
}

void post_file()
{
  const char* POSTURL =  "http://SITE/PATH/TO/CONTROLLER/ACTION";
  CURL *curl = curl_easy_init();
  char* pUrlName = "Picture.jpg";

  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_console);
  curl_httppost *formpost = 0, *lastptr  = 0;

  // add parameters and files
  curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "File1", CURLFORM_FILE, "Picture.jpg", CURLFORM_FILENAME, pUrlName, CURLFORM_END);
  curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "filename", CURLFORM_COPYCONTENTS, "Picture.jpg", CURLFORM_END);
  curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "uid", CURLFORM_COPYCONTENTS, "0012", CURLFORM_END);
  curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "timestamp", CURLFORM_COPYCONTENTS, "1636807618", CURLFORM_END);

  curl_easy_setopt(curl, CURLOPT_URL, POSTURL);
  curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);

  CURLcode res = curl_easy_perform(curl);
  curl_easy_cleanup(curl);
}

int main(void)
{	  /* In windows, this will init the winsock stuff */
  curl_global_init(CURL_GLOBAL_ALL);
  post_file();
  curl_global_cleanup();
  return 0;
}

 

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料