Files
A guide on how to work with files using the WriftAI Go client
This section demonstrates common file operations you can perform with the WriftAI Go client. These examples are not exhaustive — check the client reference for all options.
Upload a file
Create a file using wriftai.NewFile and pass it to client.Files.Upload.
wriftai.NewFile accepts the file content along with an optional MimeType. If a MimeType
is provided, it overrides automatic detection. If an empty string is
passed, it automatically determines the MIME type when possible and falls
back to application/octet-stream when it cannot be determined.
Large files are automatically split into parts and uploaded concurrently, so you don't need to do anything differently for big files, just pass them the same way.
Upload a file from disk
file, err := os.Open("report.pdf")
if err != nil {
panic(err)
}
defer file.Close()
uploadResult, err := client.Files.Upload(
context.TODO(),
wriftai.NewFile(file, ""),
nil, // no progress callback
)Upload raw bytes
data := []byte("raw file contents")
uploadResult, err := client.Files.Upload(
context.TODO(),
wriftai.NewFile(bytes.NewReader(data), ""),
nil, // no progress callback
)File-like objects
Any value that satisfies the client's wriftai.ReadSeekerAt interface (a combination of
io.ReadSeeker and io.ReaderAt) can be used as file content.
reader := strings.NewReader("file contents")
uploadResult, err := client.Files.Upload(
context.TODO(),
wriftai.NewFile(reader, ""),
nil, // no progress callback
)Override the MIME type
data := []byte("raw file contents")
uploadResult, err := client.Files.Upload(
context.TODO(),
wriftai.NewFile(bytes.NewReader(data), "application/pdf"),
nil, // no progress callback
)Track upload progress
Pass onProgress to be notified as the upload proceeds. Each time file content
is read and streamed to the request body, it's called with the number of bytes
just read and the total size of the file.
file, err := os.Open("report.pdf")
if err != nil {
panic(err)
}
defer file.Close()
onProgress := func(delta, total int64) error {
fmt.Printf("read %d more bytes (file size: %d)\n", delta, total)
return nil
}
uploadResult, err := client.Files.Upload(
context.TODO(),
wriftai.NewFile(file, ""),
onProgress,
)onProgress is called concurrently while file parts upload in parallel. If
it updates shared state, make sure that update is synchronized appropriately.