此为历史版本和 IPFS 入口查阅区,回到作品页
Phanix
IPFS 指纹 这是什么

作品指纹

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

Phanix
·
·

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

#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;
}

Original link: Phanix's Blog

CC BY-NC-ND 2.0 授权