Sample code for 30+ languages & platforms
Zig

S3 Upload Binary File from BinData

See more Amazon S3 (new) Examples

Upload a binary file contained in a BinData object to Amazon S3.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const rest = try chilkat.Rest.init();
    defer rest.deinit();

    // Connect to the Amazon AWS REST server.
    const b_tls = true;
    const port = 443;
    const b_auto_reconnect = true;
    // Make sure to connect to the region where the bucket is located..
    try rest.connect("s3-us-west-2.amazonaws.com", port, b_tls, b_auto_reconnect);

    // Provide AWS credentials for the REST call.
    const auth_aws = try chilkat.AuthAws.init();
    defer auth_aws.deinit();
    auth_aws.setAccessKey("AWS_ACCESS_KEY");
    auth_aws.setSecretKey("AWS_SECRET_KEY");
    // Use the correct region..
    auth_aws.setRegion("us-west-2");
    auth_aws.setServiceName("s3");

    try rest.setAuthAws(auth_aws);

    // Set the bucket name via the HOST header.
    // In this case, the bucket name is "chilkat.qa".
    // (Also make sure to use the correct region.)
    rest.setHost("chilkat.qa.s3-us-west-2.amazonaws.com");

    // Load a text file into memory.
    const png_data = try chilkat.BinData.init();
    defer png_data.deinit();
    png_data.loadFile("qa_data/png/anemone.png") catch {
        std.debug.print("Failed to load file from local filesystem.\n", .{});
        return;
    };

    // Indicate the Content-Type of our upload.  (This is optional)
    rest.addHeader("Content-Type", "image/png") catch {};

    // Upload the file to Amazon S3.
    const sb_response = try chilkat.StringBuilder.init();
    defer sb_response.deinit();
    rest.fullRequestBd("PUT", "/images/sea_creatures/anemone.png", png_data, sb_response) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    // Did we get a 200 response indicating success?
    const status_code = rest.getResponseStatusCode();
    if (status_code != 200) {
        std.debug.print("Error response: {s}\n", .{try sb_response.getAsString(alloc)});
        std.debug.print("Status code: {d}, Status text: {s}\n", .{ status_code, try rest.getResponseStatusText(alloc) });
        return;
    }

    std.debug.print("File successfully uploaded.\n", .{});
}