Want to send image through RabbitMQ-C but the image file too big. Receiver cannot retrieve the image. So, I converted image to base64 then put it in JSON.
const char *msg;
FILE *image1;
if (image1 = fopen(path, "rb")) {
fseek(image1, 0, SEEK_END); //used to move file pointer to a specific position
// if fseek(0 success, return 0; not successful, return non-zero value
//SEEK_END: end of file
length = ftell(image1); //ftell(): used to get total size of file after moving the file pointer at the end of the file
sprintf(tmp, "size of file: %d bytes", length);
//convert image to base64
std::string line;
std::ifstream myfile;
myfile.open(path, std::ifstream::binary);
std::vector<char> data((std::istreambuf_iterator<char>(myfile)), std::istreambuf_iterator<char>() );
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len);
std::string code = base64_encode((unsigned char*)&data[0], (unsigned int)data.size());
//convert std::string to const char
const char* base64_Image = code.c_str();
json j ;
j.push_back("Title");
j.push_back("content");
j.push_back(base64_Image);
std::string sa = j.dump();
msg = sa.c_str(); //convert std::string to const char*
}
else {
return;
}
Using RabbitMQ-C to send the message(msg) to receiver but failed [error point to here]
is const char* cannot use amqp_cstring_bytes(msg) to convert to amqp_bytes_t??
respo = amqp_basic_publish(conn, 1, amqp_cstring_bytes(exchange), amqp_cstring_bytes(routing_key),0, 0, NULL, amqp_cstring_bytes(msg));
and get this error
If there is a handler for this exception, the program may be safely continued.```
Anyone know how to send image as JSON using RabbitMQ-C & C++ ?
amqp_cstring_bytes
expects a C string, which is normally terminated by a NUL byte. Your PNG file is almost guaranteed to contain a NUL byte, so that explains why your message got cut off midway through.
As for the code in your paste: the pointer returned by sa.c_str()
is only valid while sa
is alive and unmodified. Once you exit the block containing sa
's definition, the variable is dead and buried.
Instead, get a buffer of the appropriate size with amqp_bytes_alloc
and return that:
amqp_bytes_t bytes = amqp_bytes_malloc(sa.length());
strncpy((char *)bytes.bytes, sa.c_str(), sa.length());
then pass the bytes
object to amqp_basic_publish
. Don't forget to ampqp_bytes_free
it when you're done.