We were using formdata in cpp libcurl to send data to our server using the following code:
curl_formadd(&form, &lastptr, CURLFORM_COPYNAME, "file", CURLFORM_FILE, filePath.c_str(), CURLFORM_END);
curl_easy_setopt(curl_handle, CURLOPT_HTTPPOST, form);
But now our server has been updated to accept binary in http request body & not multipart\form-data. I have found curl command to attach zipfile without using multipart\form-data as follows
curl --request POST --data-binary "@file" $URL
but I cannot find its equivalent in cpp curl. Our requirement is to upload a zipfile in the http request
You need to set the CURLOPT_READDATA
and CURLOPT_READFUNCTION
options. Curl will repeatedly call CURLOPT_READFUNCTION
with whatever you pass as CURLOPT_READDATA
as argument, until it returns 0 or CURL_READFUNC_ABORT
.
By default, libcurl assumes your READFUNCTION reads from a filehandle. The documentation shows the following example:
size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userdata)
{
FILE *readhere = (FILE *)userdata;
curl_off_t nread;
/* copy as much data as possible into the 'ptr' buffer, but no more than
'size' * 'nmemb' bytes! */
size_t retcode = fread(ptr, size, nmemb, readhere);
nread = (curl_off_t)retcode;
fprintf(stderr, "*** We read %" CURL_FORMAT_CURL_OFF_T
" bytes from file\n", nread);
return retcode;
}
void setup(char *uploadthis)
{
FILE *file = fopen("rb", uploadthis);
CURLcode result;
/* set callback to use */
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
/* pass in suitable argument to callback */
curl_easy_setopt(curl, CURLOPT_READDATA, uploadthis);
result = curl_easy_perform(curl);
}
If you wanted to read from an in-memory buffer, your READFUNCTION would need to remember an offset somewhere and memcpy
chunks every invocation until it reaches the end of the in-memory buffer.
I have used POST_FIELDS to upload a zip file. Read the zip file in binary mode into a char pointer and passed it to like this:
char * buffer;
//read file into buffer
curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)total);
curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, buffer);
Kindly correct me if I am wrong or suggest me for alternative
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.