Java Requires Chilkat v11.4.0+
Chilkat2 Java
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 theid 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 Java Downloads
import com.chilkatsoft.chilkat2.Ai;
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.ChilkatException;
public class ChilkatExample {
public static void main(String[] args) {
Ai ai = new 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.setProvider("openai");
// Use your provider's API key.
ai.setApiKey("MY_API_KEY");
// We can upload directly from a file in the filesystem, or from a Chilkat BinData.
String contentType = "image/jpeg";
String localFilePath = "qa_data/jpg/starfish.jpg";
String filenameOnServer = "starfish.jpg";
// Upload directly from a file.
String file_id = null;
try {
file_id = ai.uploadFile(localFilePath, contentType);
System.out.println("File ID: " + file_id);
System.out.println("File uploaded.");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
System.out.println("AI File Upload Failed.");
}
// Upload from the contents of a Chilkat BinData
BinData bd = new BinData();
try {
bd.loadFile(localFilePath);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
try {
file_id = ai.uploadFileBd(bd, filenameOnServer, contentType);
System.out.println("File ID: " + file_id);
System.out.println("File uploaded.");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
System.out.println("AI File Upload Failed.");
}
}
}