Sample code for 30+ languages & platforms
Unicode C++

Upload a File to an AI Provider (OpenAI, Google, Antropic, X)

See more AI Examples

Uploads a file to an AI provider using the provider's File API and returns the id that can later be used to reference the file in an query. This currently works with ChatGPT, Gemini, Claude, and Grok.

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkAiW.h>
#include <CkStringBuilderW.h>
#include <CkBinDataW.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkAiW ai;

    // The provider can be "openai", "google", "claude", "grok", or any AI that supports uploading files for later reference by ID.
    ai.put_Provider(L"openai");
    // Use your provider's API key.
    ai.put_ApiKey(L"MY_API_KEY");

    // We can upload directly from a file in the filesystem, or from a Chilkat StringBuilder, or from a Chilkat BinData.

    // Some AI providers require a content-type.
    // Also, some AI providers are picky about what content-type's are accepted.
    // Check the AI provider's documentation.
    // "application/json" is generally always acceptable.
    // "text/plain" can be used as a fallback for any text file.
    const wchar_t *contentType = L"application/json";
    const wchar_t *localFilePath = L"qa_data/hamlet.json";
    const wchar_t *filenameOnServer = L"hamlet.json";

    // Upload directly from a file.
    const wchar_t *file_id = ai.uploadFile(localFilePath,contentType);
    if (ai.get_LastMethodSuccess() == false) {
        wprintf(L"%s\n",ai.lastErrorText());
        wprintf(L"AI File Upload Failed.\n");
    }
    else {
        wprintf(L"File ID: %s\n",file_id);
        wprintf(L"File uploaded.\n");
    }

    // Upload from the contents of a StringBuilder
    CkStringBuilderW sb;
    success = sb.LoadFile(localFilePath,L"utf-8");
    if (success == false) {
        wprintf(L"%s\n",sb.lastErrorText());
        return;
    }

    file_id = ai.uploadFileSb(sb,filenameOnServer,contentType);
    if (ai.get_LastMethodSuccess() == false) {
        wprintf(L"%s\n",ai.lastErrorText());
        wprintf(L"AI File Upload Failed.\n");
    }
    else {
        wprintf(L"File ID: %s\n",file_id);
        wprintf(L"File uploaded.\n");
    }

    // Upload from the contents of a BinData
    CkBinDataW bd;
    success = bd.LoadFile(localFilePath);
    if (success == false) {
        wprintf(L"%s\n",bd.lastErrorText());
        return;
    }

    file_id = ai.uploadFileBd(bd,filenameOnServer,contentType);
    if (ai.get_LastMethodSuccess() == false) {
        wprintf(L"%s\n",ai.lastErrorText());
        wprintf(L"AI File Upload Failed.\n");
    }
    else {
        wprintf(L"File ID: %s\n",file_id);
        wprintf(L"File uploaded.\n");
    }
    }