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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
#include "cmdline.h"
#include "images.h"
#define CRLF "\r\n"
#define CRLF2 "\r\n\r\n"
int
main(int argc, char* argv[])
{
// Get database access parameters from command line if present, else
// use hard-coded values for true CGI case.
mysqlpp::examples::CommandLine cmdline(argc, argv, "root",
"nunyabinness");
if (!cmdline) {
return 1;
}
// Parse CGI query string environment variable to get image ID
unsigned int img_id = 0;
char* cgi_query = getenv("QUERY_STRING");
if (cgi_query) {
if ((strlen(cgi_query) < 4) || memcmp(cgi_query, "id=", 3)) {
std::cout << "Content-type: text/plain" << std::endl << std::endl;
std::cout << "ERROR: Bad query string" << std::endl;
return 1;
}
else {
img_id = atoi(cgi_query + 3);
}
}
else {
std::cerr << "Put this program into a web server's cgi-bin "
"directory, then" << std::endl;
std::cerr << "invoke it with a URL like this:" << std::endl;
std::cerr << std::endl;
std::cerr << " http://server.name.com/cgi-bin/cgi_jpeg?id=2" <<
std::endl;
std::cerr << std::endl;
std::cerr << "This will retrieve the image with ID 2." << std::endl;
std::cerr << std::endl;
std::cerr << "You will probably have to change some of the #defines "
"at the top of" << std::endl;
std::cerr << "examples/cgi_jpeg.cpp to allow the lookup to work." <<
std::endl;
return 1;
}
// Retrieve image from DB by ID
try {
mysqlpp::Connection con(mysqlpp::examples::db_name,
cmdline.server(), cmdline.user(), cmdline.pass());
mysqlpp::Query query = con.query();
query << "SELECT * FROM images WHERE id = " << img_id;
mysqlpp::StoreQueryResult res = query.store();
if (res && res.num_rows()) {
images img = res[0];
if (img.data.is_null) {
std::cout << "Content-type: text/plain" << CRLF2;
std::cout << "No image content!" << CRLF;
}
else {
std::cout << "X-Image-Id: " << img_id << CRLF; // for debugging
std::cout << "Content-type: image/jpeg" << CRLF;
std::cout << "Content-length: " <<
img.data.data.length() << CRLF2;
std::cout << img.data;
}
}
else {
std::cout << "Content-type: text/plain" << CRLF2;
std::cout << "ERROR: No image with ID " << img_id << CRLF;
}
}
catch (const mysqlpp::BadQuery& er) {
// Handle any query errors
std::cout << "Content-type: text/plain" << CRLF2;
std::cout << "QUERY ERROR: " << er.what() << CRLF;
return 1;
}
catch (const mysqlpp::Exception& er) {
// Catch-all for any other MySQL++ exceptions
std::cout << "Content-type: text/plain" << CRLF2;
std::cout << "GENERAL ERROR: " << er.what() << CRLF;
return 1;
}
return 0;
}
|