Skip to main content

Installation

Install the Filejar client and required dependencies:
npm install filejar hono

Setup

Create Filejar Client

Initialize the Filejar client in your Hono application:
import { Hono } from 'hono';
import Filejar from 'filejar';

const app = new Hono();

// Initialize Filejar client
const filejar = new Filejar({
  apiKey: process.env.FILEJAR_API_KEY,
});

Single File Upload Endpoint

Create an endpoint to upload a single file:
import { fileRepo } from '@/lib/db-repo';

// Single file upload endpoint
app.post('/api/files/upload', async (c) => {
  try {
    const body = await c.req.parseBody();
    const file = body.file as File;

    if (!file) {
      return c.json({ error: 'No file uploaded' }, 400);
    }

    // Upload file to Filejar
    // The body parameter is optional - Filejar will automatically use the file's original name
    const result = await filejar.upload.uploadFile([file]);
    // Or with explicit file name:
    // const result = await filejar.upload.uploadFile([file], {
    //   body: [{ file_name: file.name }],
    // });

    if (!result.response || result.response.length === 0) {
      return c.json({ error: 'Failed to upload file' }, 500);
    }

    const uploadResult = result.response[0];
    const acknowledged = result.acknowledge[0];
    
    // Check if acknowledgment was successful
    if ('error' in acknowledged) {
      return c.json({ error: acknowledged.error }, 500);
    }

    // Construct file URL using the key
    const fileUrl = `https://cdn.filejar.dev/${uploadResult.key}`;
    
    // Store file metadata in database
    const savedFile = await fileRepo.create({
      key: uploadResult.key,
      uploadId: uploadResult.upload_id,
      originalName: file.name,
      contentType: acknowledged.content_type,
      size: acknowledged.size,
      url: fileUrl,
      uploadedBy: c.get('authId'), // Assuming you have auth middleware
    });

    return c.json({
      success: true,
      file: savedFile,
    });
  } catch (error) {
    console.error('Upload error:', error);
    if (error instanceof Filejar.APIError) {
      return c.json({ 
        error: error.message,
        status: error.status 
      }, error.status || 500);
    }
    return c.json({ error: 'Failed to upload file' }, 500);
  }
});

Multiple Files Upload Endpoint

Create an endpoint to upload multiple files:
// Multiple files upload endpoint
app.post('/api/files/upload-multiple', async (c) => {
  try {
    const body = await c.req.parseBody();
    const files = Array.isArray(body.files) ? body.files as File[] : [body.files as File].filter(Boolean);

    if (!files || files.length === 0) {
      return c.json({ error: 'No files uploaded' }, 400);
    }

    // Upload all files to Filejar
    // The body parameter is optional - Filejar will automatically use each file's original name
    const result = await filejar.upload.uploadFile(files);
    // Or with explicit file names:
    // const result = await filejar.upload.uploadFile(files, {
    //   body: files.map(file => ({ file_name: file.name })),
    // });

    if (!result.response || result.response.length === 0) {
      return c.json({ error: 'Failed to upload files' }, 500);
    }

    // Store file metadata in database
    const filePromises = result.response.map(async (uploadResult, index) => {
      const originalFile = files[index];
      const acknowledged = result.acknowledge[index];
      
      // Skip if acknowledgment failed
      if ('error' in acknowledged) {
        console.error(`Failed to acknowledge ${originalFile.name}:`, acknowledged.error);
        return null;
      }

      // Construct file URL using the key
      const fileUrl = `https://cdn.filejar.dev/${uploadResult.key}`;
      
      const savedFile = await fileRepo.create({
        key: uploadResult.key,
        uploadId: uploadResult.upload_id,
        originalName: originalFile.name,
        contentType: acknowledged.content_type,
        size: acknowledged.size,
        url: fileUrl,
        uploadedBy: c.get('authId'),
      });

      return savedFile;
    });

    const uploadedFiles = (await Promise.all(filePromises)).filter(file => file !== null);

    return c.json({
      success: true,
      files: uploadedFiles,
      count: uploadedFiles.length,
    });
  } catch (error) {
    console.error('Upload error:', error);
    if (error instanceof Filejar.APIError) {
      return c.json({ 
        error: error.message,
        status: error.status 
      }, error.status || 500);
    }
    return c.json({ error: 'Failed to upload files' }, 500);
  }
});

Retrieve Files from Database

Create an endpoint to retrieve file information using the stored key:
import { fileRepo } from '@/lib/db-repo';

// Get file by ID
app.get('/api/files/:id', async (c) => {
  try {
    const id = c.req.param('id');

    const file = await fileRepo.findById(id);

    if (!file) {
      return c.json({ error: 'File not found' }, 404);
    }

    return c.json(file);
  } catch (error) {
    console.error('Error retrieving file:', error);
    return c.json({ error: 'Failed to retrieve file' }, 500);
  }
});

// Get all files
app.get('/api/files', async (c) => {
  try {
    const files = await fileRepo.findAll();

    return c.json({ files });
  } catch (error) {
    console.error('Error retrieving files:', error);
    return c.json({ error: 'Failed to retrieve files' }, 500);
  }
});

Client-Side Usage

Upload Single File

// Client-side: Upload single file
async function uploadFile(file: File) {
  const formData = new FormData();
  formData.append('file', file);

  const response = await fetch(`${API_BASE_URL}/api/files/upload`, {
    method: 'POST',
    body: formData,
  });

  const data = await response.json();
  return data.file; // Contains id, filejarId, filejarKey, name, url
}

Upload Multiple Files

// Client-side: Upload multiple files
async function uploadFiles(files: File[]) {
  const formData = new FormData();
  files.forEach(file => {
    formData.append('files', file);
  });

  const response = await fetch(`${API_BASE_URL}/api/files/upload-multiple`, {
    method: 'POST',
    body: formData,
  });

  const data = await response.json();
  return data.files; // Array of file objects
}

Retrieve File

Simply use the file key to construct the URL:
// Direct URL access using the file key
const fileUrl = `https://cdn.filejar.dev/${key}`;

// Example: Display file in img tag
<img src={`https://cdn.filejar.dev/${fileKey}`} alt="Uploaded file" />

Complete Example

Here’s a complete Hono server setup with all endpoints:
import { Hono } from 'hono';
import Filejar from 'filejar';
import { fileRepo } from '@/lib/db-repo';

const app = new Hono();

// Initialize Filejar client
const filejar = new Filejar({
  apiKey: process.env.FILEJAR_API_KEY,
});

// Single file upload
app.post('/api/files/upload', async (c) => {
  // ... single upload code from above
});

// Multiple files upload
app.post('/api/files/upload-multiple', async (c) => {
  // ... multiple upload code from above
});

// Get file by ID
app.get('/api/files/:id', async (c) => {
  // ... get file code from above
});

// Get all files
app.get('/api/files', async (c) => {
  // ... get all files code from above
});

export default app;