Sending an image to ftp server from gchar buffer (libcurl)

≯℡__Kan透↙ 提交于 2019-12-02 01:33:19

The read_callback() is a function which CURL calls when it need to obtain data that will be uploaded to the server. Imagine that read_callback() is something similar to fread(). When called it performs any voodoo-mumbo-jumbo that is needed, but in the end uploadable data must be stored in *ptr buffer, which is curl's internal buffer. For your in-memory buffer memcpy() will do just fine as body of read_callback(), so you don't need real fread() at all.

size * nmemb tells you how big buffer curl has reserved for a single chunk of data. The last void* is a pointer which was set by CURLOPT_READDATA option - it's a do-what-ever-you-need-with-it kind of pointer, so it can point to a structure containing data which you're uploading and a some additional info e.g. current progress.

You may use this as a sample:

#include <gdk-pixbuf/gdk-pixbuf.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <string.h>

struct transfer
{
    gchar *buf;
    gsize total;
    size_t uploaded;
};

static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *data)
{
    struct transfer * tr = data;
    size_t left = tr->total - tr->uploaded;
    size_t max_chunk = size * nmemb;
    size_t retcode = left < max_chunk ? left : max_chunk;

    memcpy(ptr, tr->buf + tr->uploaded, retcode); // <-- voodoo-mumbo-jumbo :-)

    tr->uploaded += retcode;  // <-- save progress
    return retcode;
} 

int main()
{
    GdkPixbuf * gbuffer = NULL;
    GError * error = NULL;
    gchar * buffer;
    gsize size;
    g_type_init();
    gbuffer = gdk_pixbuf_new_from_file("g.png", &error);
    gdk_pixbuf_save_to_buffer(gbuffer, &buffer, &size, "jpeg", &error, NULL);

    struct transfer tr = {buffer, size, 0};

    CURL *easyhandle = curl_easy_init();
    curl_easy_setopt(easyhandle, CURLOPT_READFUNCTION, read_callback); 
    curl_easy_setopt(easyhandle, CURLOPT_READDATA, &tr); // <-- this will be *data in read_callback()
    curl_easy_setopt(easyhandle, CURLOPT_UPLOAD, 1L); 
    curl_easy_setopt(easyhandle, CURLOPT_URL, "http://example.com/upload.php");
    CURLcode rc = curl_easy_perform(easyhandle);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!