Skip to main content
Files can be retrieved using their unique file ID with proper content headers and security controls.
This endpoint returns the actual file content with appropriate MIME type headers. Files are access-controlled based on company permissions.

Endpoint

curl -X GET "https://api.g2cplatform.com/v2/companies/{COMPANY_ID}/files/{FILE_ID}" \
  -H "X-API-Key: YOUR_API_KEY" \
  --output downloaded_file.pdf

Request

HTTP Method

GET

URL

https://api.g2cplatform.com/v2/companies/{COMPANY_ID}/files/{FILE_ID}

Path Parameters

ParameterTypeRequiredDescription
COMPANY_IDstring (UUID)Company identifier
FILE_IDstring (UUID)File identifier

Query Parameters

ParameterTypeDefaultDescription
downloadbooleanfalseForce download as attachment

Headers

X-API-Key: YOUR_API_KEY

Response

Success Response (200 OK)

The response contains the raw file content with appropriate headers:
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 1234567
Content-Disposition: inline; filename="document.pdf"
Cache-Control: private, max-age=3600
ETag: "abc123def456"

[Binary file content]

Response Headers

HeaderDescriptionExample
Content-TypeMIME type of the fileapplication/pdf
Content-LengthFile size in bytes1234567
Content-DispositionHow browser should handle fileinline; filename="document.pdf"
Cache-ControlCache directivesprivate, max-age=3600
ETagFile version identifier"abc123def456"

Error Responses

404 Not Found

{
  "error": "File not found",
  "code": "FILE_NOT_FOUND",
  "timestamp": "2025-08-03T10:30:00Z"
}

401 Unauthorized

{
  "error": "Invalid or missing API key",
  "code": "UNAUTHORIZED",
  "timestamp": "2025-08-03T10:30:00Z"
}

403 Forbidden

{
  "error": "Access denied to file",
  "code": "FILE_ACCESS_DENIED",
  "timestamp": "2025-08-03T10:30:00Z"
}

Implementation Examples

Basic File Download

async function downloadFile(companyId, fileId, filename = null) {
  try {
    const response = await fetch(
      `https://api.g2cplatform.com/v2/companies/${companyId}/files/${fileId}`,
      {
        headers: {
          'X-API-Key': process.env.G2C_API_KEY
        }
      }
    );

    if (response.ok) {
      const blob = await response.blob();

      // Get filename from header or use provided name
      const contentDisposition = response.headers.get('Content-Disposition');
      const headerFilename = contentDisposition
        ?.split('filename=')[1]?.replace(/"/g, '');

      const finalFilename = filename || headerFilename || 'download';

      console.log('✅ File downloaded successfully:', finalFilename);
      return { blob, filename: finalFilename };
    } else {
      const error = await response.json();
      throw new Error(`Download failed: ${error.error}`);
    }
  } catch (error) {
    console.error('❌ File download error:', error.message);
    throw error;
  }
}

// Usage
const { blob, filename } = await downloadFile('company-uuid', 'file-uuid');

Download to Browser

async function downloadToBrowser(companyId, fileId) {
  try {
    const response = await fetch(
      `https://api.g2cplatform.com/v2/companies/${companyId}/files/${fileId}?download=true`,
      {
        headers: {
          'X-API-Key': process.env.G2C_API_KEY
        }
      }
    );

    if (response.ok) {
      const blob = await response.blob();
      const contentDisposition = response.headers.get('Content-Disposition');
      const filename = contentDisposition
        ?.split('filename=')[1]?.replace(/"/g, '') || 'download';

      // Create and trigger download
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = filename;
      a.style.display = 'none';

      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);

      // Clean up
      setTimeout(() => URL.revokeObjectURL(url), 100);

      console.log('✅ File download initiated:', filename);
    } else {
      const error = await response.json();
      throw new Error(`Download failed: ${error.error}`);
    }
  } catch (error) {
    console.error('❌ Browser download error:', error.message);
    throw error;
  }
}

Display Image in Browser

async function displayImage(companyId, fileId, imgElement) {
  try {
    const response = await fetch(
      `https://api.g2cplatform.com/v2/companies/${companyId}/files/${fileId}`,
      {
        headers: {
          'X-API-Key': process.env.G2C_API_KEY
        }
      }
    );

    if (response.ok) {
      const blob = await response.blob();
      const imageUrl = URL.createObjectURL(blob);

      imgElement.src = imageUrl;
      imgElement.onload = () => {
        // Clean up URL after image loads
        URL.revokeObjectURL(imageUrl);
      };

      console.log('✅ Image loaded successfully');
    } else {
      const error = await response.json();
      throw new Error(`Image load failed: ${error.error}`);
    }
  } catch (error) {
    console.error('❌ Image display error:', error.message);
    imgElement.alt = 'Failed to load image';
  }
}

// Usage
const imgElement = document.getElementById('asset-photo');
await displayImage('company-uuid', 'file-uuid', imgElement);

Get File as Base64

async function getFileAsBase64(companyId, fileId) {
  try {
    const response = await fetch(
      `https://api.g2cplatform.com/v2/companies/${companyId}/files/${fileId}`,
      {
        headers: {
          'X-API-Key': process.env.G2C_API_KEY
        }
      }
    );

    if (response.ok) {
      const blob = await response.blob();

      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
          // Remove data URL prefix to get just the base64 string
          const base64 = reader.result.split(',')[1];
          resolve(base64);
        };
        reader.onerror = reject;
        reader.readAsDataURL(blob);
      });
    } else {
      const error = await response.json();
      throw new Error(`Base64 conversion failed: ${error.error}`);
    }
  } catch (error) {
    console.error('❌ Base64 conversion error:', error.message);
    throw error;
  }
}

// Usage
const base64Data = await getFileAsBase64('company-uuid', 'file-uuid');
console.log('Base64 length:', base64Data.length);

Batch File Download

async function downloadMultipleFiles(companyId, fileIds) {
  const results = [];

  for (const fileId of fileIds) {
    try {
      const { blob, filename } = await downloadFile(companyId, fileId);
      results.push({
        success: true,
        fileId,
        filename,
        size: blob.size
      });

      // Add delay to avoid overwhelming the server
      await new Promise(resolve => setTimeout(resolve, 200));
    } catch (error) {
      results.push({
        success: false,
        fileId,
        error: error.message
      });
    }
  }

  const successful = results.filter(r => r.success);
  const failed = results.filter(r => !r.success);

  console.log(`✅ Downloaded ${successful.length} files successfully`);
  if (failed.length > 0) {
    console.log(`❌ Failed to download ${failed.length} files`);
  }

  return { successful, failed };
}

// Usage
const fileIds = ['file-1', 'file-2', 'file-3'];
const results = await downloadMultipleFiles('company-uuid', fileIds);

Stream Large Files

async function streamLargeFile(companyId, fileId, onProgress) {
  try {
    const response = await fetch(
      `https://api.g2cplatform.com/v2/companies/${companyId}/files/${fileId}`,
      {
        headers: {
          'X-API-Key': process.env.G2C_API_KEY
        }
      }
    );

    if (!response.ok) {
      const error = await response.json();
      throw new Error(`Stream failed: ${error.error}`);
    }

    const contentLength = +response.headers.get('Content-Length');
    const reader = response.body.getReader();
    const chunks = [];
    let receivedLength = 0;

    while (true) {
      const { done, value } = await reader.read();

      if (done) break;

      chunks.push(value);
      receivedLength += value.length;

      const progress = contentLength ? (receivedLength / contentLength) * 100 : 0;
      if (onProgress) {
        onProgress(progress, receivedLength, contentLength);
      }
    }

    // Combine chunks into blob
    const blob = new Blob(chunks);
    const filename = response.headers.get('Content-Disposition')
      ?.split('filename=')[1]?.replace(/"/g, '') || 'download';

    console.log('✅ Large file streamed successfully');
    return { blob, filename };

  } catch (error) {
    console.error('❌ File streaming error:', error.message);
    throw error;
  }
}

// Usage with progress tracking
await streamLargeFile('company-uuid', 'large-file-uuid', (progress, loaded, total) => {
  console.log(`Progress: ${progress.toFixed(1)}% (${loaded}/${total} bytes)`);
  document.getElementById('progress-bar').style.width = `${progress}%`;
});

Use Cases

Document Viewer

class DocumentViewer {
  constructor(companyId, apiKey) {
    this.companyId = companyId;
    this.apiKey = apiKey;
  }

  async viewDocument(fileId) {
    try {
      const response = await fetch(
        `https://api.g2cplatform.com/v2/companies/${this.companyId}/files/${fileId}`,
        {
          headers: { 'X-API-Key': this.apiKey }
        }
      );

      if (response.ok) {
        const blob = await response.blob();
        const url = URL.createObjectURL(blob);

        // Open in new window/tab
        const newWindow = window.open(url, '_blank');

        // Clean up after some time
        setTimeout(() => {
          URL.revokeObjectURL(url);
          if (newWindow) newWindow.close();
        }, 60000);

        return true;
      } else {
        const error = await response.json();
        throw new Error(error.error);
      }
    } catch (error) {
      console.error('Failed to view document:', error.message);
      return false;
    }
  }
}
class ImageGallery {
  constructor(companyId, apiKey) {
    this.companyId = companyId;
    this.apiKey = apiKey;
  }

  async loadImages(fileIds, container) {
    const imagePromises = fileIds.map(async (fileId) => {
      try {
        const response = await fetch(
          `https://api.g2cplatform.com/v2/companies/${this.companyId}/files/${fileId}`,
          {
            headers: { 'X-API-Key': this.apiKey }
          }
        );

        if (response.ok) {
          const blob = await response.blob();
          const img = document.createElement('img');
          img.src = URL.createObjectURL(blob);
          img.style.maxWidth = '200px';
          img.style.margin = '10px';
          img.style.cursor = 'pointer';

          // Add click handler for full view
          img.onclick = () => this.viewFullImage(fileId);

          container.appendChild(img);
        }
      } catch (error) {
        console.error(`Failed to load image ${fileId}:`, error);
      }
    });

    await Promise.all(imagePromises);
  }

  async viewFullImage(fileId) {
    const response = await fetch(
      `https://api.g2cplatform.com/v2/companies/${this.companyId}/files/${fileId}`,
      {
        headers: { 'X-API-Key': this.apiKey }
      }
    );

    if (response.ok) {
      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      window.open(url, '_blank');
    }
  }
}

Security Considerations

File access is controlled by:
  • API key permissions
  • Company ownership
  • Object associations
  • File-level access controls
When handling downloaded files:
  • Validate MIME types match expectations
  • Verify file sizes are reasonable
  • Scan for malware if applicable
  • Use Content Security Policy headers
Files are protected through:
  • HTTPS encryption in transit
  • Access logging and audit trails
  • Company-scoped permissions
  • Secure storage infrastructure

MIME Type Handling

Common MIME types you’ll encounter:
File TypeMIME TypeExtension
PDF Documentapplication/pdf.pdf
JPEG Imageimage/jpeg.jpg, .jpeg
PNG Imageimage/png.png
Word Documentapplication/msword.doc
Excel Spreadsheetapplication/vnd.ms-excel.xls
Plain Texttext/plain.txt
CSV Filetext/csv.csv

Next Steps