libcurl post图片 base64编码

#include "httppost.h"
#include <curl/curl.h>
#include <string.h>
#include <sys/time.h>  


#define POSTURL "http://121.40.93.5:7300/dbzf/router/rest?method=api/picture/upload"  
#ifndef MAX_PATH
#define MAX_PATH 256
#endif

const char * base64char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

char * base64_encode( const unsigned char * bindata, char * base64, int binlength )
{
    int i, j;
    unsigned char current;

    for ( i = 0, j = 0 ; i < binlength ; i += 3 )
    {
        current = (bindata[i] >> 2) ;
        current &= (unsigned char)0x3F;
        base64[j++] = base64char[(int)current];

        current = ( (unsigned char)(bindata[i] << 4 ) ) & ( (unsigned char)0x30 ) ;
        if ( i + 1 >= binlength )
        {
            base64[j++] = base64char[(int)current];
            base64[j++] = '=';
            base64[j++] = '=';
            break;
        }
        current |= ( (unsigned char)(bindata[i+1] >> 4) ) & ( (unsigned char) 0x0F );
        base64[j++] = base64char[(int)current];

        current = ( (unsigned char)(bindata[i+1] << 2) ) & ( (unsigned char)0x3C ) ;
        if ( i + 2 >= binlength )
        {
            base64[j++] = base64char[(int)current];
            base64[j++] = '=';
            break;
        }
        current |= ( (unsigned char)(bindata[i+2] >> 6) ) & ( (unsigned char) 0x03 );
        base64[j++] = base64char[(int)current];

        current = ( (unsigned char)bindata[i+2] ) & ( (unsigned char)0x3F ) ;
        base64[j++] = base64char[(int)current];
    }
    base64[j] = '\0';
    return base64;
}

int base64_decode( const char * base64, unsigned char * bindata )
{
    int i, j;
    unsigned char k;
    unsigned char temp[4];
    for ( i = 0, j = 0; base64[i] != '\0' ; i += 4 )
    {
        memset( temp, 0xFF, sizeof(temp) );
        for ( k = 0 ; k < 64 ; k ++ )
        {
            if ( base64char[k] == base64[i] )
                temp[0]= k;
        }
        for ( k = 0 ; k < 64 ; k ++ )
        {
            if ( base64char[k] == base64[i+1] )
                temp[1]= k;
        }
        for ( k = 0 ; k < 64 ; k ++ )
        {
            if ( base64char[k] == base64[i+2] )
                temp[2]= k;
        }
        for ( k = 0 ; k < 64 ; k ++ )
        {
            if ( base64char[k] == base64[i+3] )
                temp[3]= k;
        }

        bindata[j++] = ((unsigned char)(((unsigned char)(temp[0] << 2))&0xFC)) |
                ((unsigned char)((unsigned char)(temp[1]>>4)&0x03));
        if ( base64[i+2] == '=' )
            break;

        bindata[j++] = ((unsigned char)(((unsigned char)(temp[1] << 4))&0xF0)) |
                ((unsigned char)((unsigned char)(temp[2]>>2)&0x0F));
        if ( base64[i+3] == '=' )
            break;

        bindata[j++] = ((unsigned char)(((unsigned char)(temp[2] << 6))&0xF0)) |
                ((unsigned char)(temp[3]&0x3F));
    }
    return j;
}

void encode(FILE * fp_in, FILE * fp_out)
{
    unsigned char bindata[2050];
    char base64[4096];
    size_t bytes;
    while ( !feof( fp_in ) )
    {
        bytes = fread( bindata, 1, 2049, fp_in );
        base64_encode( bindata, base64, bytes );
        fprintf( fp_out, "%s", base64 );
    }
}

void decode(FILE * fp_in, FILE * fp_out)
{
    int i;
    unsigned char bindata[2050];
    char base64[4096];
    size_t bytes;
    while ( !feof( fp_in ) )
    {
        for ( i = 0 ; i < 2048 ; i ++ )
        {
            base64[i] = fgetc(fp_in);
            if ( base64[i] == EOF )
                break;
            else if ( base64[i] == '\n' || base64[i] == '\r' )
                i --;
        }
        bytes = base64_decode( base64, bindata );
        fwrite( bindata, bytes, 1, fp_out );
    }
}
int HttpPostJpegString(char *buf,int buf_len)
{
FILE *pictureSrc;
printf("buf=%s buf_len=%d\n",buf,buf_len);
pictureSrc=fopen("/tmp/webproject/pictureSrc.jpg","w+");
if (!pictureSrc) {
return -1;
}
printf("buf=%s\n",buf);
fwrite(buf, 1, buf_len,pictureSrc);
fseek(pictureSrc,0L,SEEK_SET);
HttpPostJpegFile(pictureSrc);
}
int HttpPostJpegFile(FILE *fp)
{
CURL *curl;  
CURLM *multi_handle;  
int still_running;
long int flength,first;
struct curl_httppost *formpost=NULL;  
struct curl_httppost *lastptr=NULL;  
struct curl_slist *headerlist=NULL;  
static const char buf[] = "Expect:"; 
char *didi;
FILE *pEncode;
pEncode=fopen("/tmp/webproject/pEncode.jpg","w+");
if (!pEncode) {
return -1;
}
encode(fp, pEncode);
fclose(fp);
printf("httpPostJpeg\n");
fseek(pEncode,0L,SEEK_SET);
printf("The file pointer is at byte %ld\n", ftell(pEncode));
first=ftell(pEncode);
printf("ftell success \n");
fseek(pEncode,0L,SEEK_END);
printf("The file pointer is at byte %ld\n", ftell(pEncode));
flength=ftell(pEncode)-first;
fseek(pEncode,0L,SEEK_SET);
printf("The file flength is at byte %ld\n", flength);
    /*read the data and display it*/  
didi=(char *) malloc(flength);
if(didi==NULL)
exit(1);
fread(didi,1,flength,pEncode);
fclose(pEncode);
curl_formadd(&formpost,  
 &lastptr,
 CURLFORM_COPYNAME, "imgBase64",  
 CURLFORM_COPYCONTENTS, didi, CURLFORM_END);  
curl = curl_easy_init();  
multi_handle = curl_multi_init();  
/* initalize custom header list (stating that Expect: 100-continue is not 
   wanted */  
headerlist = curl_slist_append(headerlist, buf);  
if(curl && multi_handle) {
  /* what URL that receives this POST */  
  curl_easy_setopt(curl, CURLOPT_URL,POSTURL);  
  curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);  
  curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);  
  curl_multi_add_handle(multi_handle, curl);  
  curl_multi_perform(multi_handle, &still_running);  
  do {
struct timeval timeout;  
int rc; /* select() return code */
fd_set fdread;
fd_set fdwrite;  
fd_set fdexcep;  
int maxfd = -1;  
long curl_timeo = -1;  
FD_ZERO(&fdread);  
FD_ZERO(&fdwrite);
FD_ZERO(&fdexcep);
/* set a suitable timeout to play around with */  
timeout.tv_sec = 1;  
timeout.tv_usec = 0;  
curl_multi_timeout(multi_handle, &curl_timeo);
if(curl_timeo >= 0) {  
  timeout.tv_sec = curl_timeo / 1000;  
  if(timeout.tv_sec > 1)  
timeout.tv_sec = 1;  
  else
timeout.tv_usec = (curl_timeo % 1000) * 1000;  
}  
/* get file descriptors from the transfers */  
curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);  
/* In a real-world program you OF COURSE check the return code of the 
   function calls. On success, the value of maxfd is guaranteed to be 
   greater or equal than -1.  We call select(maxfd + 1, ...), specially in 
   case of (maxfd == -1), we call select(0, ...), which is basically equal 
   to sleep. */  
rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);  
switch(rc) {  
case -1:  
  /* select error */  
  break;  
case 0:  
default:  
  /* timeout or readable/writable sockets */  
  printf("perform!\n");  
  curl_multi_perform(multi_handle, &still_running);  
  printf("running: %d!\n", still_running);
  break;  
}  
  } while(still_running);  
  curl_multi_cleanup(multi_handle);  
  /* always cleanup */
  curl_easy_cleanup(curl);
  /* then cleanup the formpost chain */  
  curl_formfree(formpost);
  /* free slist */
  curl_slist_free_all (headerlist);  
}
free(didi);
return 0;  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是使用Qt和libcurl库发送POST请求上传图片的示例代码: ```c++ #include <QCoreApplication> #include <QDebug> #include <QFile> #include <QByteArray> #include <curl/curl.h> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); // 读取图片文件 QFile file("test.jpg"); if (!file.open(QIODevice::ReadOnly)) { qDebug() << "Failed to open file!"; return a.exec(); } QByteArray image = file.readAll(); file.close(); // 初始化libcurl curl_global_init(CURL_GLOBAL_ALL); CURL *curl = curl_easy_init(); if (!curl) { qDebug() << "Failed to initialize curl!"; return a.exec(); } // 设置请求URL和POST数据 curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/upload"); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, image.data()); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, image.size()); // 发送请求并获取响应 CURLcode res = curl_easy_perform(curl); if (res != CURLE_OK) { qDebug() << "Failed to send request: " << curl_easy_strerror(res); } // 清理资源 curl_easy_cleanup(curl); curl_global_cleanup(); return a.exec(); } ``` 在上面的代码中,我们首先使用QFile读取了一个名为“test.jpg”的图片文件,并将其存储在QByteArray中。接下来,我们初始化了libcurl库,并使用curl_easy_init函数创建了一个CURL句柄。然后,我们使用curl_easy_setopt函数设置了请求URL和POST数据,并使用curl_easy_perform函数发送了POST请求。最后,我们清理了资源并结束了程序。 需要注意的是,该示例代码没有处理任何异常情况,如文件不存在、curl初始化失败、请求失败等。在实际应用中,需要根据具体情况进行异常处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dingdongkk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值