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

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

Rust

let ai = chilkat::Ai::new();

// The provider can be "openai", "google", "claude", "grok", or any AI that supports uploading files for later reference by ID.
ai.set_provider("openai");
// Use your provider's API key.
ai.set_api_key("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.
let content_type = "application/json".to_string();
let local_file_path = "qa_data/hamlet.json".to_string();
let filename_on_server = "hamlet.json".to_string();

// Upload directly from a file.
let mut file_id = ai.upload_file(&local_file_path, &content_type).unwrap_or_default();
if !ai.last_method_success() {
    println!("{}", ai.last_error_text());
    println!("AI File Upload Failed.");
} else {
    println!("File ID: {}", file_id);
    println!("File uploaded.");
}

// Upload from the contents of a StringBuilder
let sb = chilkat::StringBuilder::new();
if sb.load_file(&local_file_path, "utf-8").is_err() {
    println!("{}", sb.last_error_text());
    return;
}

file_id = ai.upload_file_sb(&sb, &filename_on_server, &content_type).unwrap_or_default();
if !ai.last_method_success() {
    println!("{}", ai.last_error_text());
    println!("AI File Upload Failed.");
} else {
    println!("File ID: {}", file_id);
    println!("File uploaded.");
}

// Upload from the contents of a BinData
let bd = chilkat::BinData::new();
if bd.load_file(&local_file_path).is_err() {
    println!("{}", bd.last_error_text());
    return;
}

file_id = ai.upload_file_bd(&bd, &filename_on_server, &content_type).unwrap_or_default();
if !ai.last_method_success() {
    println!("{}", ai.last_error_text());
    println!("AI File Upload Failed.");
} else {
    println!("File ID: {}", file_id);
    println!("File uploaded.");
}