#include <stdio.h>
#include <sys/io.h> 
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <time.h> 
#include <curl/curl.h>
#include <sys/stat.h> 
#include <dirent.h>
#include <sys/inotify.h>  

static char g_last_name[20]="upload_audio.mp3";

int sendPostFile();
unsigned long get_file_size();

unsigned long get_file_size()  
{  
    unsigned long filesize = -1;      
    struct stat statbuff;  
    if(stat("/home/user/upload_audio.mp3", &statbuff) < 0){  
        return filesize;  
    }else{  
        filesize = statbuff.st_size;  
    }  
    return filesize;  
}  

int sendPostFile(){
  CURL *curl;
  CURLcode res;
  char filesize[15]={0};
  sprintf(filesize, "%lu", get_file_size);

  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);
   
   /* Fill in the file upload field */ 
   
   curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "uploadfile",
               CURLFORM_FILE, g_name,			   
               CURLFORM_CONTENTTYPE, "application/octet-stream", 
               CURLFORM_END);
     
   printf("curl_formadd filesize\n");  
   curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "filesize",
               CURLFORM_COPYCONTENTS, filesize,
               CURLFORM_END); 
	
  
   printf("curl_formadd submit\n");  
   curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "upfile",
               CURLFORM_COPYCONTENTS, "commit",
               CURLFORM_END);
    
   UPLOG("curl curl_easy_init\n");
   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, POST_FILE_URL);
    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));
	  return -1;
	} 
    /* always cleanup */ 
    curl_easy_cleanup(curl); 
    /* then cleanup the formpost chain */ 
    curl_formfree(formpost);
    /* free slist */ 
    curl_slist_free_all (headerlist);
  }
  return 0;
}

void main(int argc, char *argv[]){  
    if(0==sendPostFile()){
		printf("sendPostFile success\n"); 
	}else{					
		printf("sendPostFile failed\n"); 
	}
}

 

Logo

更多推荐