On 6/23/22 11:08, Taw via curl-library wrote:
Hello,

I am trying to do a multipart/form-data upload with cURL + json + custom headers and I am not sure how to do it properly. I want something equivalent to this cmdline command:

curl -H 'Content-Type: multipart/form-data' -H 'x-custom-header: custom value' https://url_to_upload -F "file=@file_to_upload" -F "params=@params.json"

If you have a working curl command like above, it is always possible to use option --libcurl to generate the equivalent C code program pattern: see https://curl.se/docs/manpage.html#--libcurl and https://everything.curl.dev/libcurl/libcurl. You can set the file argument to "-" to have the generated code written on stdout.

1. For JSON should I use CURLOPT_POSTFIELDS or curl_mime_addpart/curl_mime_name/curl_mime_data?
CURLOPT_POSTFIELDS and CURLOPT_MIMEPOST are mutually exclusive options: If you use the former, data is supposed to be already formatted. CURLOPT_MIMEPOST allows you to define each part separately and format the whole post from them. If you want to send the JSON data in a form part named "params", the simplest way is to use the mime API.
2. For headers should I use CURLOPT_HTTPHEADER or curl_mime_headers?
CURLOPT_HTTPHEADER sets http REQUEST headers, curl_mime_headers set mime PARTS headers. The latter's scope is limited to the part itself.
3. Can I reuse a mime handle for multiple files? Is there any way to reset it, so I won't do curl_mime_init/curl_mime_free for each file?

I suppose you mean a reuse for a subsequent request on the same curl handle? In this case, yes you can reuse it providing you do not need to delete old parts, only modify them or add some.

There is no way to reset a whole mime handle, but you can still reapply new parameters to PARTS (providing you have kept part handles around) using the regular curl_mime_*() functions.


Please note the "Content-Type: multipart/form-data" request header is the default for http(s) with CURLOPT_MIMEPOST: there's no need to set it explicitly. You may however set "Content-Type: application/json" to the "params" part, if needed by your server.

--
Unsubscribe: https://lists.haxx.se/listinfo/curl-library
Etiquette:   https://curl.se/mail/etiquette.html

Reply via email to