> ## Documentation Index
> Fetch the complete documentation index at: https://docs.invaro.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# File Upload Best Practices

> Learn how to optimize file uploads and handle documents effectively

<Note>
  Follow these guidelines to ensure optimal document processing results and efficient API usage.
</Note>

## Document Requirements

<CardGroup cols={2}>
  <Card title="Supported Formats" icon="file">
    * PDF (preferred for documents)
    * PNG (for scanned documents)
    * JPEG (for scanned documents)
  </Card>

  <Card title="File Specifications" icon="gear">
    * Resolution: 300 DPI minimum
    * Max file size: 10MB per file
    * Max batch size: 50 files
  </Card>
</CardGroup>

## Implementation Guide

### 1. File Optimization

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={null}
    const sharp = require('sharp');

    async function optimizeImage(inputBuffer) {
      return await sharp(inputBuffer)
        .resize(2000, 2000, {
          fit: 'inside',
          withoutEnlargement: true
        })
        .jpeg({
          quality: 85,
          progressive: true
        })
        .toBuffer();
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    from PIL import Image
    import io

    def optimize_image(input_bytes):
        with Image.open(io.BytesIO(input_bytes)) as img:
            # Convert to RGB if needed
            if img.mode in ('RGBA', 'P'):
                img = img.convert('RGB')
            
            # Resize if too large
            max_size = 2000
            ratio = min(max_size/img.width, max_size/img.height)
            if ratio < 1:
                new_size = (int(img.width * ratio), int(img.height * ratio))
                img = img.resize(new_size, Image.LANCZOS)
            
            # Save optimized image
            output = io.BytesIO()
            img.save(output, 'JPEG', quality=85, optimize=True)
            return output.getvalue()
    ```
  </Tab>
</Tabs>

### 2. Batch Processing

<Info>For multiple files, use batch uploading to reduce API calls and improve performance.</Info>

```javascript theme={null}
async function batchUpload(files, batchSize = 10) {
  const batches = [];
  for (let i = 0; i < files.length; i += batchSize) {
    batches.push(files.slice(i, i + batchSize));
  }

  const results = [];
  for (const batch of batches) {
    const batchResults = await Promise.all(
      batch.map(file => uploadFile(file))
    );
    results.push(...batchResults);
  }

  return results;
}
```

### 3. Validation

<Warning>Always validate files before uploading to prevent processing errors.</Warning>

```javascript theme={null}
function validateFile(file) {
  const validations = {
    size: file.size <= 10 * 1024 * 1024, // 10MB limit
    type: ['application/pdf', 'image/jpeg', 'image/png'].includes(file.type),
    name: /^[a-zA-Z0-9-_\.]+$/.test(file.name)
  };

  const errors = Object.entries(validations)
    .filter(([_, valid]) => !valid)
    .map(([key]) => `Invalid file ${key}`);

  return {
    valid: errors.length === 0,
    errors
  };
}
```

### 4. Error Handling

<Info>Implement retry logic to handle transient failures gracefully.</Info>

```javascript theme={null}
async function uploadWithRetry(file, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await uploadFile(file);
    } catch (error) {
      if (!isRetryableError(error) || attempt === maxRetries - 1) {
        throw error;
      }
      
      const delay = Math.pow(2, attempt) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}
```

## Troubleshooting Guide

<AccordionGroup>
  <Accordion title="File Size Issues" icon="file-circle-exclamation">
    If your file exceeds 10MB:

    * Use the optimization code above for images
    * Compress PDFs using Adobe Acrobat or similar tools
    * Split large documents into smaller parts
    * Maintain image quality while reducing file size
  </Accordion>

  <Accordion title="Upload Failures" icon="cloud-arrow-up">
    Common causes and solutions:

    * Network issues: Check your internet connection
    * Invalid format: Verify file type and size
    * Rate limits: Implement exponential backoff
    * Server errors: Retry with error handling
  </Accordion>

  <Accordion title="Processing Errors" icon="gears">
    To ensure successful processing:

    * Use high-quality, clear documents
    * Maintain proper document orientation
    * Check for file corruption
    * Follow format specifications
  </Accordion>
</AccordionGroup>

## Best Practices Summary

<CardGroup cols={2}>
  <Card title="Document Quality" icon="image">
    <Check>Use high resolution (300 DPI+)</Check>
    <Check>Ensure proper lighting</Check>
    <Check>Maintain clear text</Check>
    <Check>Keep original aspect ratio</Check>
  </Card>

  <Card title="Upload Strategy" icon="cloud-arrow-up">
    <Check>Batch similar documents</Check>
    <Check>Validate before upload</Check>
    <Check>Monitor progress</Check>
    <Check>Handle errors gracefully</Check>
  </Card>

  <Card title="Error Prevention" icon="shield-check">
    <Check>Verify file formats</Check>
    <Check>Check size limits</Check>
    <Check>Implement retries</Check>
    <Check>Log all failures</Check>
  </Card>

  <Card title="Performance" icon="bolt">
    <Check>Use batch uploads</Check>
    <Check>Optimize file size</Check>
    <Check>Cache when possible</Check>
    <Check>Monitor rate limits</Check>
  </Card>
</CardGroup>

<Note>
  Need help? Contact our support team:

  * Email: [support@invaro.ai](mailto:support@invaro.ai)
  * Status: [status.invaro.ai](https://status.invaro.ai)
</Note>
