Sample code for 30+ languages & platforms
B4X Requires Chilkat v11.4.0+

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

See more AI Examples

Uploads an image 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 and Gemini, but not other AI's. Most AI's currently don't have the ability to reference pre-uploaded image data in conversations.

Chilkat B4X Downloads

B4X
Dim success As Boolean = False

Dim ai As ChilkatAi
ai.Initialize("ai")

'  Can currently be "openai" or "google" because these are the only AI's that can reference pre-loaded image data by file ID.
ai.Provider = "openai"
'  Use your provider's API key.
ai.ApiKey = "MY_API_KEY"

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

Dim contentType As String = "image/jpeg"
Dim localFilePath As String = "qa_data/jpg/starfish.jpg"
Dim filenameOnServer As String = "starfish.jpg"

'  Upload directly from a file.
Dim file_id As String = ai.UploadFile(localFilePath, contentType)
If ai.LastMethodSuccess = False Then
    Log(ai.LastErrorText)
    Log("AI File Upload Failed.")
Else
    Log("File ID: " & file_id)
    Log("File uploaded.")
End If


'  Upload from the contents of a Chilkat BinData
Dim bd As ChilkatBinData
bd.Initialize
success = bd.LoadFile(localFilePath)
If success = False Then
    Log(bd.LastErrorText)
    Return
End If

file_id = ai.UploadFileBd(bd, filenameOnServer, contentType)
If ai.LastMethodSuccess = False Then
    Log(ai.LastErrorText)
    Log("AI File Upload Failed.")
Else
    Log("File ID: " & file_id)
    Log("File uploaded.")
End If