logo_smallAxellero.io

Download File

Download files from the sandbox environment to external systems with comprehensive format support and secure transfer protocols.

Download File

Securely download files from the sandbox environment with support for multiple formats, compression options, and transfer protocols while maintaining data integrity and security.

📥 Secure File Downloads

File downloads include integrity verification, size validation, and format checking to ensure safe and reliable file transfers from the sandbox environment.

Overview

The Download File tool enables secure file retrieval from the sandbox environment, supporting various file formats, compression options, and transfer methods with comprehensive security controls and download management.

Key Features

  • Multi-Format Support - Download text, binary, compressed, and archive files
  • Integrity Verification - Checksum validation and corruption detection
  • Compression Options - Automatic compression for large file transfers
  • Transfer Protocols - Secure HTTP, HTTPS, and direct download methods
  • Progress Monitoring - Real-time download progress and status tracking

Methods

downloadFile

Download files from the sandbox environment securely.

ParameterTypeRequiredDescription
filePathStringYesPath to the file in sandbox environment
downloadFormatStringNoDownload format: 'original', 'zip', 'tar.gz' (default: 'original')
compressionLevelNumberNoCompression level 1-9 for compressed formats (default: 6)
includeMetadataBooleanNoInclude file metadata in download (default: false)
chunkSizeNumberNoDownload chunk size in bytes (default: 1048576)
maxFileSizeNumberNoMaximum allowed file size in bytes (default: 100MB)
{
  "filePath": "/sandbox/data/report.pdf",
  "downloadFormat": "original",
  "includeMetadata": true
}

Output:

  • success (Boolean) - Download operation success status
  • downloadUrl (String) - Secure download URL with expiration
  • fileName (String) - Downloaded file name
  • fileSize (Number) - File size in bytes
  • checksum (String) - SHA-256 checksum for integrity verification
  • mimeType (String) - File MIME type
  • metadata (Object) - File metadata (if requested)
    • created (String) - Creation timestamp
    • modified (String) - Last modification timestamp
    • permissions (String) - File permissions
  • expirationTime (String) - Download URL expiration timestamp

Supported File Types

Document Files

Media Files

Archive Files

Supported Formats:

  • ZIP - ZIP archive format
  • TAR - Tape Archive format
  • TAR.GZ - Compressed tar archives
  • 7Z - 7-Zip archive format

Archive Features:

  • Content validation
  • Compression verification
  • Directory structure preservation
  • Selective extraction support

Download Workflows

Single File Download

# Download individual file with metadata
def download_single_file(file_path):
    """Download a single file from sandbox."""
    
    result = downloadFile({
        "filePath": file_path,
        "downloadFormat": "original",
        "includeMetadata": True
    })
    
    if result['success']:
        print(f"Download URL: {result['downloadUrl']}")
        print(f"File size: {result['fileSize']} bytes")
        print(f"Checksum: {result['checksum']}")
        print(f"Expires: {result['expirationTime']}")
        
        # Verify file integrity
        if verify_checksum(result['downloadUrl'], result['checksum']):
            print("✅ File integrity verified")
        else:
            print("❌ File integrity check failed")
    
    return result

# Usage
download_result = download_single_file("/sandbox/output/final_report.pdf")

Batch File Download

# Download multiple files as compressed archive
def download_batch_files(file_paths):
    """Download multiple files as a single archive."""
    
    import tempfile
    import zipfile
    import os
    
    # Create temporary archive
    temp_archive = tempfile.mktemp(suffix='.zip')
    
    try:
        with zipfile.ZipFile(temp_archive, 'w', zipfile.ZIP_DEFLATED) as zf:
            for file_path in file_paths:
                # Add each file to archive
                if os.path.exists(file_path):
                    zf.write(file_path, os.path.basename(file_path))
        
        # Download the archive
        result = downloadFile({
            "filePath": temp_archive,
            "downloadFormat": "original",
            "includeMetadata": False
        })
        
        # Cleanup temporary file
        os.unlink(temp_archive)
        
        return result
        
    except Exception as e:
        print(f"Batch download failed: {str(e)}")
        return {"success": False, "error": str(e)}

# Usage
file_list = [
    "/sandbox/data/dataset1.csv",
    "/sandbox/data/dataset2.csv", 
    "/sandbox/reports/summary.pdf"
]
batch_result = download_batch_files(file_list)

Conditional Download

# Download files based on conditions
def conditional_download(directory_path, conditions):
    """Download files matching specific conditions."""
    
    import os
    import datetime
    
    downloaded_files = []
    
    for root, dirs, files in os.walk(directory_path):
        for file in files:
            file_path = os.path.join(root, file)
            file_stats = os.stat(file_path)
            
            # Check file size condition
            if conditions.get('max_size') and file_stats.st_size > conditions['max_size']:
                continue
            
            # Check modification date
            if conditions.get('modified_after'):
                mod_time = datetime.datetime.fromtimestamp(file_stats.st_mtime)
                if mod_time < conditions['modified_after']:
                    continue
            
            # Check file extension
            if conditions.get('extensions'):
                file_ext = os.path.splitext(file)[1].lower()
                if file_ext not in conditions['extensions']:
                    continue
            
            # Download qualifying file
            result = downloadFile({
                "filePath": file_path,
                "downloadFormat": "original"
            })
            
            if result['success']:
                downloaded_files.append({
                    "path": file_path,
                    "url": result['downloadUrl'],
                    "size": result['fileSize']
                })
    
    return downloaded_files

# Usage example
conditions = {
    'max_size': 10 * 1024 * 1024,  # 10MB
    'extensions': ['.pdf', '.xlsx', '.csv'],
    'modified_after': datetime.datetime.now() - datetime.timedelta(days=7)
}

recent_files = conditional_download("/sandbox/output", conditions)

Security and Validation

File Integrity Verification

🔐 Security Verification

Always verify file integrity using provided checksums before processing downloaded files. This ensures data hasn't been corrupted during transfer.

import hashlib
import requests

def verify_checksum(download_url, expected_checksum):
    """Verify downloaded file integrity."""
    
    response = requests.get(download_url, stream=True)
    sha256_hash = hashlib.sha256()
    
    # Calculate checksum while downloading
    for chunk in response.iter_content(chunk_size=8192):
        if chunk:
            sha256_hash.update(chunk)
    
    calculated_checksum = sha256_hash.hexdigest()
    return calculated_checksum == expected_checksum

Download Security Controls

Access Controls:

  • Time-limited download URLs (default: 1 hour expiration)
  • Single-use download tokens
  • IP address validation
  • Rate limiting per session

Content Validation:

  • File type verification
  • Size limit enforcement
  • Malware scanning (for executable files)
  • Content structure validation

Transfer Security:

  • HTTPS-only downloads
  • Encrypted transfer protocols
  • Integrity checksums
  • Progress monitoring

Error Handling

Common Download Issues

Error TypeCauseResolution
File Not FoundFile path doesn't existVerify file path and permissions
Size Limit ExceededFile exceeds maximum size limitUse compression or split files
Permission DeniedInsufficient file access rightsCheck file permissions and ownership
Corruption DetectedFile integrity check failedRe-download file or check source
Network TimeoutDownload timeout during transferRetry with smaller chunk size

Error Response Format

{
  "success": false,
  "error": {
    "type": "FILE_NOT_FOUND",
    "message": "The specified file does not exist",
    "details": {
      "filePath": "/sandbox/missing/file.pdf",
      "suggestions": [
        "Check file path spelling",
        "Verify file exists in sandbox",
        "Check file permissions"
      ]
    }
  }
}

Best Practices

💡 Download Best Practices

Security Guidelines

  1. Verify Integrity - Always check checksums for important files
  2. Validate URLs - Ensure download URLs are from trusted sources
  3. Monitor Expiration - Track URL expiration times
  4. Secure Storage - Store downloaded files securely

Performance Optimization

  1. Compression Usage - Use compression for large files
  2. Batch Operations - Group multiple small files
  3. Chunk Size Tuning - Optimize chunk size for network conditions
  4. Progress Monitoring - Track download progress for large transfers

File Management

  1. Naming Conventions - Use descriptive file names
  2. Version Control - Track file versions and updates
  3. Cleanup Procedures - Remove temporary files after processing
  4. Metadata Preservation - Include metadata for important files

Integration Patterns

With Code Execution Tools

# Generate and download reports from code execution
def generate_and_download_report():
    """Generate analysis report and download it."""
    
    # Execute analysis code
    analysis_code = """
import pandas as pd
import matplotlib.pyplot as plt

# Load and analyze data
data = pd.read_csv('/sandbox/data/sales.csv')
summary = data.describe()

# Create visualization
plt.figure(figsize=(10, 6))
plt.plot(data['date'], data['sales'])
plt.title('Sales Over Time')
plt.savefig('/sandbox/output/sales_chart.png')

# Save analysis results
summary.to_csv('/sandbox/output/analysis_summary.csv')
print("Analysis completed")
    """
    
    # Execute the analysis
    exec_result = codeExecution({
        "language": "python",
        "code": analysis_code
    })
    
    if exec_result['success']:
        # Download generated files
        chart_download = downloadFile({
            "filePath": "/sandbox/output/sales_chart.png",
            "downloadFormat": "original"
        })
        
        summary_download = downloadFile({
            "filePath": "/sandbox/output/analysis_summary.csv", 
            "downloadFormat": "zip"
        })
        
        return {
            "chart": chart_download,
            "summary": summary_download
        }
    
    return None

# Execute workflow
results = generate_and_download_report()

Next Steps: Use with Code Execution to generate files for download, or see File Metadata for file information extraction.