Sample code for 30+ languages & platforms
Zig

REST File Upload (multipart/form-data)

See more REST Examples

Demonstrates how to upload a file using multipart/form-data.

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 HTTP server using TLS.
    const b_tls = true;
    const port = 443;
    const b_auto_reconnect = true;
    // Make sure to replace "www.chilkatsoft.com" with your domain..
    rest.connect("www.chilkatsoft.com", port, b_tls, b_auto_reconnect) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    const file_stream = try chilkat.Stream.init();
    defer file_stream.deinit();
    file_stream.setSourceFile("qa_data/jpg/starfish.jpg");

    rest.addHeader("Content-Type", "multipart/form-data") catch {};

    rest.setPartSelector("1");
    rest.addHeader("Content-Type", "image/jpg") catch {};
    rest.addHeader("Content-Disposition", "form-data; name=\"filename\"; filename=\"starfish.jpg\"") catch {};
    rest.setMultipartBodyStream(file_stream) catch {};
    rest.setPartSelector("0");

    _ = rest.fullRequestMultipart(alloc, "POST", "/the_uri_path_to_receive_the_upload") catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    if (rest.getResponseStatusCode() != 200) {
        std.debug.print("Received error response code: {d}\n", .{rest.getResponseStatusCode()});
        return;
    }

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