Upload your pictures to Twitpic using C++/libcurl

by ranjith on April 5, 2009

Here is a small program that will upload an image file less than 4MB to twitpic.com. The API endpoint that I used here is http://twitpic.com/api/upload". This won’t send an update to the twitter. Use uploadAndPost.

Needless to say this requires libcurl. Grab it from here in source or binary form.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <sstream>
#include <curl/curl.h>
 
#define END_POINT "http://twitpic.com/api/upload"
#define EXPECT_ARGS 4
 
size_t write_data(void *buffer, size_t size, size_t nmemb, void* userp)
{
 
	std::stringstream strmResponse;
	size_t nReal = size * nmemb;
	strmResponse << std::string((char*)buffer, size*nmemb);
	std::string sLine("");
	while (getline(strmResponse, sLine)) {
		std::cout << sLine.c_str() << std::endl;
	}
	return nReal;
}
 
int main (int argc, char * const argv[]) {
 
	int result = 0;
	CURL* hCurl = NULL;
	CURLcode hResult;
	std::string sUser("");
	std::string sPass("");
	std::string sFileName("");
	//Curl for form data
	struct curl_httppost *post = NULL;
	struct curl_httppost *last = NULL;
	try{
		if(argc < EXPECT_ARGS) {
			std::cout << "Usage twitpic_upload twitterUserName twiiterPassword fileName" << std::endl;
			throw false;
		}
		//Get the require params from command line args
		sUser     = argv[1];
		sPass     = argv[2];
		sFileName = argv[3];
 
		//Initialize curl, just don't let easy_init to do it for you
		curl_global_init(CURL_GLOBAL_ALL);
		//Handle to the curl
		hCurl = curl_easy_init();
		if(NULL == hCurl) {
			throw false;
		}
		//Construct the form
		curl_formadd(&post, &last, CURLFORM_COPYNAME, "username", CURLFORM_COPYCONTENTS, sUser.c_str(), CURLFORM_END);
		curl_formadd(&post, &last, CURLFORM_COPYNAME, "password", CURLFORM_COPYCONTENTS, sPass.c_str(), CURLFORM_END);
		curl_formadd(&post, &last, CURLFORM_COPYNAME, "media", CURLFORM_FILE, sFileName.c_str(), CURLFORM_END);
		//Specify the API Endpoint
		hResult = curl_easy_setopt(hCurl,CURLOPT_URL, END_POINT);
		//Specify the HTTP Method
		hResult = curl_easy_setopt(hCurl, CURLOPT_HTTPPOST, post);
		//Post Away !!!
		hResult = curl_easy_perform(hCurl);
		if(hResult != CURLE_OK){
			std::cout << "Cannot find the twitpic site " << std::endl;
			throw false;
		}
	}
	catch (...) {
		result = -1;
	}
	curl_formfree(post);
    curl_easy_cleanup(hCurl);
	curl_global_cleanup();
    return result;
}

blog comments powered by Disqus

Previous post: Adding libcurl to Xcode’s linker settings

Next post: Plug and Pray