post实现图片上传

上传图片方式有很多,今天给大家介绍一个开源的库使用的方法,希望对大家有所帮助!

 


#include 

#include 

#include 


int main(int argc, char *argv[])
{
  CURL *curl;
  CURLcode res;

  struct curl_httppost *formpost=NULL;
  struct curl_httppost *lastptr=NULL;
  struct curl_slist *headerlist=NULL;
  static const char buf[] = "Expect:";

  curl_global_init(CURL_GLOBAL_ALL);

  curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "file", CURLFORM_FILE, "/opt/testZ.jpg", CURLFORM_END);
                curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "filesize", CURLFORM_PTRCONTENTS, "20569", CURLFORM_END);
                curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "filename", CURLFORM_PTRCONTENTS, "testZ.jpg", CURLFORM_END);
                curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "filetime", CURLFORM_PTRCONTENTS, "2019-03-13 16:16:10", CURLFORM_END);
                curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "tlength", CURLFORM_PTRCONTENTS, "0", CURLFORM_END);
                curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "filepath", CURLFORM_PTRCONTENTS, "filepath", CURLFORM_END);

  curl = curl_easy_init();
  /* initalize custom header list (stating that Expect: 100-continue is not 
     wanted */
    headerlist = curl_slist_append(headerlist, buf);
  if(curl)
  {
    //UPLOG("curl true begin post\n");
    /* what URL that receives this POST */
    curl_easy_setopt(curl, CURLOPT_URL, "http://xx.xx.xx.xx:8080/upload");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
    //curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, 1613); 
    /* Perform the request, res will get the return code */
    res = curl_easy_perform(curl);
    /* Check for errors */
    if(res != CURLE_OK)
    {
      fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
      //UPLOG("curl url_easy_perform() failed:%s \n",curl_easy_strerror(res));
      curl_easy_cleanup(curl);
    /* then cleanup the formpost chain */
      curl_formfree(formpost);
    /* free slist */
      curl_slist_free_all (headerlist);

      printf("upload is failure!!!\n");
      return -1;
    }

    printf("upload is successful!!!\n");
    /* always cleanup */
    curl_easy_cleanup(curl);
    /* then cleanup the formpost chain */
    curl_formfree(formpost);
    /* free slist */
    curl_slist_free_all (headerlist);
  }

   return 0;
}

 

你可能感兴趣的:(linux学习,网络通讯)