or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced.mdclient-class.mdfile-handling.mdindex.mdstandalone-functions.mdtypes.md
tile.json

file-handling.mddocs/

File Operations

The @gradio/client package provides comprehensive file handling capabilities, supporting multiple input formats, upload operations, and automatic type conversion. The file system is designed to work seamlessly across browser and Node.js environments.

Capabilities

FileData Class

The FileData class represents file information and content for upload and processing operations.

/**
 * Represents file data with metadata for Gradio operations
 */
class FileData {
  /** File path (for local files or server references) */
  path?: string;
  /** File URL (for remote files) */
  url?: string;
  /** Original filename */
  orig_name?: string;
  /** File size in bytes */
  size?: number;
  /** Blob data (for browser file handling) */
  blob?: Blob;
  /** Whether file should be treated as a stream */
  is_stream?: boolean;
  /** MIME type of the file */
  mime_type?: string;
  /** Alternative text description */
  alt_text?: string;
  /** Base64 encoded file content */
  b64?: string;
  /** Additional metadata */
  meta?: Record<string, any>;

  constructor(data: {
    path?: string;
    url?: string;
    orig_name?: string;
    size?: number;
    blob?: Blob;
    is_stream?: boolean;
    mime_type?: string;
    alt_text?: string;
    b64?: string;
    meta?: Record<string, any>;
  });
}

Usage Examples:

import { FileData } from "@gradio/client";

// Local file reference
const localFile = new FileData({
  path: "./documents/report.pdf",
  orig_name: "quarterly-report.pdf",
  mime_type: "application/pdf"
});

// Remote file reference
const remoteFile = new FileData({
  url: "https://example.com/image.jpg",
  orig_name: "sample-image.jpg",
  mime_type: "image/jpeg"
});

// Blob-based file (browser)
const blob = new Blob(["file content"], { type: "text/plain" });
const blobFile = new FileData({
  blob: blob,
  orig_name: "generated.txt",
  mime_type: "text/plain",
  size: blob.size
});

// Base64 encoded file
const b64File = new FileData({
  b64: "data:text/plain;base64,SGVsbG8gV29ybGQ=",
  orig_name: "hello.txt",
  mime_type: "text/plain"
});

// Streaming file
const streamFile = new FileData({
  path: "./large-video.mp4",
  is_stream: true,
  mime_type: "video/mp4"
});

File Upload Functions

Core functions for uploading files to Gradio applications.

/**
 * Upload raw files to Gradio server
 * @param root_url - Base URL of the Gradio application
 * @param files - Array of File or Blob objects to upload
 * @param upload_id - Optional upload session identifier
 * @returns Promise resolving to upload response with file URLs
 */
function upload_files(
  root_url: string,
  files: (Blob | File)[],
  upload_id?: string
): Promise<UploadResponse>;

/**
 * Upload FileData objects with full metadata support
 * @param file_data - Array of FileData objects to upload
 * @param root_url - Base URL of the Gradio application
 * @param upload_id - Optional upload session identifier
 * @param max_file_size - Maximum file size limit in bytes
 * @returns Promise resolving to processed FileData array
 */
function upload(
  file_data: FileData[],
  root_url: string,
  upload_id?: string,
  max_file_size?: number
): Promise<(FileData | null)[] | null>;

Usage Examples:

import { upload_files, upload, FileData } from "@gradio/client";

// Upload raw files
const fileInput = document.getElementById("fileInput") as HTMLInputElement;
const files = Array.from(fileInput.files || []);
const response = await upload_files("https://gradio-app-url", files);
console.log("Uploaded files:", response);

// Upload with FileData objects
const fileDataArray = [
  new FileData({
    path: "./image1.jpg",
    orig_name: "photo1.jpg",
    mime_type: "image/jpeg"
  }),
  new FileData({
    path: "./image2.png", 
    orig_name: "photo2.png",
    mime_type: "image/png"
  })
];

const result = await upload(
  fileDataArray,
  "https://gradio-app-url",
  "session-123",
  10 * 1024 * 1024 // 10MB limit
);

// Check upload results
result?.forEach((fileData, index) => {
  if (fileData) {
    console.log(`File ${index} uploaded:`, fileData.url);
  } else {
    console.log(`File ${index} upload failed`);
  }
});

File Processing Functions

Utility functions for preparing and converting file data.

/**
 * Convert File objects to FileData objects
 * @param files - Array of File objects to convert
 * @param is_stream - Whether files should be treated as streams
 * @returns Promise resolving to array of FileData objects
 */
function prepare_files(files: File[], is_stream?: boolean): Promise<FileData[]>;

/**
 * Process various file input types into appropriate objects
 * @param file_or_url - File, string URL, Blob, or Buffer to process
 * @returns FileData, Blob, or Command object based on input type
 */
function handle_file(file_or_url: File | string | Blob | Buffer): FileData | Blob | Command;

Usage Examples:

import { prepare_files, handle_file } from "@gradio/client";

// Prepare browser files for upload
const fileInput = document.getElementById("files") as HTMLInputElement;
const files = Array.from(fileInput.files || []);
const fileDataArray = await prepare_files(files);

// Prepare streaming files
const streamingFiles = await prepare_files(files, true);

// Handle different input types
const inputs = [
  new File(["content"], "test.txt"),
  "https://example.com/image.jpg",
  new Blob(["data"]),
  Buffer.from("binary data")
];

const processed = inputs.map(input => handle_file(input));
console.log("Processed files:", processed);

// File type detection
const textFile = handle_file(new File(["text"], "doc.txt"));
console.log(textFile instanceof FileData); // true

const imageUrl = handle_file("https://example.com/photo.jpg");  
console.log(imageUrl instanceof FileData); // true

const rawBlob = handle_file(new Blob(["data"]));
console.log(rawBlob instanceof Blob); // true

Command Class

The Command class represents local file upload commands for special file operations.

/**
 * Represents a local file upload command
 */
class Command {
  /** Command type identifier */
  type: string;
  /** Command string/action */
  command: string;
  /** File metadata */
  meta: {
    path: string;
    name: string;
    orig_path: string;
  };
  /** Associated file data */
  fileData?: FileData;

  constructor(
    command: string,
    meta: {
      path: string;
      name: string;
      orig_path: string;
    }
  );
}

Usage Examples:

import { Command } from "@gradio/client";

// Create file upload command
const uploadCommand = new Command("upload", {
  path: "/tmp/uploaded/file.txt",
  name: "file.txt", 
  orig_path: "./local/file.txt"
});

// Commands are typically created automatically by handle_file()
const result = handle_file("./local-file.txt");
if (result instanceof Command) {
  console.log("Created upload command for:", result.meta.name);
}

File Format Support

Supported File Types

The @gradio/client supports a wide range of file formats:

Images:

  • JPEG, PNG, GIF, WebP, BMP, TIFF
  • SVG (vector graphics)

Documents:

  • PDF, DOC, DOCX, TXT, RTF
  • CSV, JSON, XML

Media:

  • MP4, AVI, MOV, WebM (video)
  • MP3, WAV, OGG, FLAC (audio)

Data:

  • JSON, CSV, TSV, Parquet
  • HDF5, NumPy arrays (.npy)

Archives:

  • ZIP, TAR, GZ, RAR

MIME Type Detection

import { FileData } from "@gradio/client";

// Automatic MIME type detection
const file = new File(["content"], "document.pdf");
const fileData = new FileData({
  blob: file,
  orig_name: file.name
  // mime_type automatically detected from file extension
});

// Manual MIME type specification
const customFile = new FileData({
  blob: new Blob(["custom data"]),
  orig_name: "data.custom",
  mime_type: "application/x-custom-format"
});

Environment-Specific Usage

Browser Environment

// File input handling
const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const files = Array.from(target.files || []);
  
  // Convert to FileData
  const fileDataArray = await prepare_files(files);
  
  // Upload to Gradio
  const result = await upload(fileDataArray, "https://app-url");
  console.log("Upload complete:", result);
};

// Drag and drop support
const handleDrop = async (event: DragEvent) => {
  event.preventDefault();
  const files = Array.from(event.dataTransfer?.files || []);
  const fileDataArray = await prepare_files(files);
  
  // Process dropped files
  const result = await upload(fileDataArray, "https://app-url");
};

// Blob creation from canvas
const canvas = document.getElementById("canvas") as HTMLCanvasElement;
canvas.toBlob(async (blob) => {
  if (blob) {
    const fileData = new FileData({
      blob: blob,
      orig_name: "canvas-image.png",
      mime_type: "image/png"
    });
    
    const result = await upload([fileData], "https://app-url");
  }
});

Node.js Environment

import { readFile } from "fs/promises";
import { FileData, upload } from "@gradio/client";

// Read local file
const fileBuffer = await readFile("./document.pdf");
const fileData = new FileData({
  path: "./document.pdf",
  orig_name: "document.pdf",
  mime_type: "application/pdf",
  size: fileBuffer.length
});

// Upload from file system
const result = await upload([fileData], "https://app-url");

// Process Buffer data
const bufferData = Buffer.from("text content", "utf-8");
const processedFile = handle_file(bufferData);

Upload Response Types

UploadResponse

interface UploadResponse {
  /** Array of uploaded file information */
  files: Array<{
    /** Server-assigned file path */
    name: string;
    /** File size in bytes */
    size: number;
    /** Server URL for accessing the file */
    url: string;
    /** Original filename */
    orig_name: string;
    /** Whether upload completed successfully */
    is_file: boolean;
  }>;
  /** Upload session identifier */
  upload_id?: string;
}

File Upload Patterns

import { Client, FileData } from "@gradio/client";

const client = await Client.connect("https://app-url");

// Single file upload with prediction
const fileData = new FileData({
  path: "./image.jpg",
  orig_name: "photo.jpg"
});

const result = await client.predict("/analyze-image", [fileData]);

// Multiple file upload
const files = [
  new FileData({ path: "./doc1.pdf" }),
  new FileData({ path: "./doc2.pdf" })
];

const result = await client.predict("/process-documents", [files]);

// Mixed input types
const mixedInputs = [
  "text parameter",
  new FileData({ path: "./file.txt" }),
  42,
  { option: "value" }
];

const result = await client.predict("/mixed-endpoint", mixedInputs);

Error Handling

File Upload Errors

import { upload, FileData } from "@gradio/client";

try {
  const fileData = new FileData({
    path: "./large-file.mp4",
    orig_name: "video.mp4"
  });
  
  const result = await upload(
    [fileData],
    "https://app-url", 
    undefined,
    50 * 1024 * 1024 // 50MB limit
  );
  
  if (!result || result[0] === null) {
    console.error("File upload failed");
  }
} catch (error) {
  if (error.message.includes("File size")) {
    console.error("File too large");
  } else if (error.message.includes("network")) {
    console.error("Network error during upload");
  } else {
    console.error("Upload error:", error.message);
  }
}

File Processing Errors

import { handle_file, prepare_files } from "@gradio/client";

// Handle invalid file inputs
try {
  const result = handle_file("invalid://url");
} catch (error) {
  console.error("Invalid file input:", error.message);
}

// Check file preparation results
try {
  const files = [/* File objects */];
  const fileDataArray = await prepare_files(files);
  
  fileDataArray.forEach((fileData, index) => {
    if (!fileData.mime_type) {
      console.warn(`File ${index}: Could not detect MIME type`);
    }
  });
} catch (error) {
  console.error("File preparation failed:", error.message);
}

Performance Considerations

Large File Handling

import { FileData } from "@gradio/client";

// Use streaming for large files
const largeFile = new FileData({
  path: "./large-dataset.parquet",
  is_stream: true,
  mime_type: "application/octet-stream"
});

// Split large uploads into chunks
const chunkSize = 10 * 1024 * 1024; // 10MB chunks
const files = /* array of large files */;

for (let i = 0; i < files.length; i += 3) {
  const chunk = files.slice(i, i + 3);
  const result = await upload(chunk, "https://app-url");
  console.log(`Uploaded chunk ${i / 3 + 1}`);
}

Memory Optimization

// Avoid loading large files into memory
const fileData = new FileData({
  path: "./large-file.bin",  // File path instead of blob
  is_stream: true            // Stream processing
});

// Use URLs for remote files instead of downloading
const remoteFile = new FileData({
  url: "https://example.com/large-file.zip"  // Reference, not download
});

See Also

  • @gradio/client - Main package overview and file upload examples
  • Client Class Reference - Client-based file upload methods
  • Standalone Functions - Function-based file operations
  • Advanced Topics - Protocol details and optimization
  • Type Reference - Complete file-related type definitions