Light Logo
JavaScript SDK (v0.54.0)Guides

Files

A guide on how to work with files using the WriftAI JavaScript client

This section demonstrates common file operations you can perform with the WriftAI JavaScript client. These examples are not exhaustive — check the client reference for all options.

Upload a file

files.upload takes FileData, which wraps the file's contents along with an optional mimeType. If provided, mimeType overrides any automatically inferred value; If omitted, it is inferred from the file object's type property when available, otherwise from the file extension in it's name property. Falls back to application/octet-stream if it cannot be inferred.

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.

From a browser file input (<input type="file">):

import { FileData } from 'wriftai';

const uploadResult = await wriftai.files.upload(new FileData(input.files[0]));

From constructed data:

import { FileData } from 'wriftai';

const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
const uploadResult = await wriftai.files.upload(new FileData(blob));

From a fetch response:

import { FileData } from 'wriftai';

const res = await fetch('https://example.com/image.png');
const uploadResult = await wriftai.files.upload(
  new FileData(await res.blob(), 'image/png'),
);

MIME type cannot be inferred from blob()'s return type therefore a mimeType override is provided, otherwise it would have fallen back to application/octet-stream.

From a file path (requires node:fs):

import { readFile } from 'node:fs/promises';
import { FileData } from 'wriftai';

const uploadResult = await wriftai.files.upload(
  new FileData(await readFile('./photo.png'), 'image/png'),
);

MIME type cannot be inferred from readFile()'s return type therefore a mimeType override is provided, otherwise it would have fallen back to application/octet-stream.

For large files, use openAsBlob to stream from disk without loading the entire file into memory (requires node:fs):

import { openAsBlob } from 'node:fs';
import { FileData } from 'wriftai';

const uploadResult = await wriftai.files.upload(
  new FileData(await openAsBlob('./large-video.mp4'), 'video/mp4'),
);

MIME type cannot be inferred from openAsBlob()'s return type therefore a mimeType override is provided, otherwise it would have fallen back to application/octet-stream.

On this page