Sample code for 30+ languages & platforms
Ruby

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 Ruby Downloads

Ruby
require 'chilkat'

success = false

ai = Chilkat::CkAi.new()

# The provider can be "openai", "google", "claude", "grok", or any AI that supports uploading files for later reference by ID.
ai.put_Provider("openai")
# Use your provider's API key.
ai.put_ApiKey("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.
contentType = "application/json"
localFilePath = "qa_data/hamlet.json"
filenameOnServer = "hamlet.json"

# Upload directly from a file.
file_id = ai.uploadFile(localFilePath,contentType)
if (ai.get_LastMethodSuccess() == false)
    print ai.lastErrorText() + "\n";
    print "AI File Upload Failed." + "\n";
else
    print "File ID: " + file_id + "\n";
    print "File uploaded." + "\n";
end

# Upload from the contents of a StringBuilder
sb = Chilkat::CkStringBuilder.new()
success = sb.LoadFile(localFilePath,"utf-8")
if (success == false)
    print sb.lastErrorText() + "\n";
    exit
end

file_id = ai.uploadFileSb(sb,filenameOnServer,contentType)
if (ai.get_LastMethodSuccess() == false)
    print ai.lastErrorText() + "\n";
    print "AI File Upload Failed." + "\n";
else
    print "File ID: " + file_id + "\n";
    print "File uploaded." + "\n";
end

# Upload from the contents of a BinData
bd = Chilkat::CkBinData.new()
success = bd.LoadFile(localFilePath)
if (success == false)
    print bd.lastErrorText() + "\n";
    exit
end

file_id = ai.uploadFileBd(bd,filenameOnServer,contentType)
if (ai.get_LastMethodSuccess() == false)
    print ai.lastErrorText() + "\n";
    print "AI File Upload Failed." + "\n";
else
    print "File ID: " + file_id + "\n";
    print "File uploaded." + "\n";
end