tutorials 9 min de lectura

Advanced File Upload Forms with Validation in Qödiak

Learn how to build powerful file upload forms with robust validation in Qödiak. Step‑by‑step guide for secure, multi‑file and custom logic.

Q
Qodiak Team
Product & Engineering
Advanced File Upload Forms with Validation in Qödiak

File upload forms are a cornerstone of many digital experiences, from job applications to medical record submissions. In this tutorial you’ll discover how to create file upload forms with validation in Qödiak that are secure, user‑friendly, and ready for real‑world compliance requirements.

Why Validation Matters for File Uploads

Common Risks and Compliance

Unvalidated uploads can expose your app to malware, oversized files that break storage limits, and even legal violations when handling sensitive data. A few typical risks include:

  • Malicious scripts hidden in image or document files.
  • Excessive file size that exhausts the 100 MB free storage quota.
  • Unsupported formats that render poorly on mobile devices.
  • Regulatory breaches when personal health information is stored without proper controls.

Benefits of Built‑in Validation

Qödiak’s visual page builder lets you set client‑side constraints instantly, while the sandboxed JavaScript engine offers server‑side checks for deeper security. Combining both layers gives you:

  • Instant feedback that reduces user frustration.
  • Protection against oversized or disallowed files before they hit your storage.
  • Flexibility to enforce business‑specific rules (e.g., only doctors can upload PDFs).

Setting Up a Basic File Upload Component

Adding the FileUpload component

Start a new page in the Qödiak visual editor and drag the FileUpload component from the Form Inputs palette onto the canvas. The component appears as a simple button with a default label “Choose file”.

For quick access to the component’s settings, click the gear icon. You’ll see fields for Accepted File Types, Maximum Size (MB), and a toggle for Multiple Files.

Configuring accepted file types and size limits

In the settings panel, type the MIME types you want to allow, separated by commas. For example:

image/jpeg, image/png, application/pdf

Set the maximum size to 10 MB to stay well within the free tier limit. Remember that Qödiak stores uploads in the built‑in submission storage, so each file counts against the 100 MB quota.

Save the page, then click Publish. Your form now accepts only the defined types and sizes, providing the first line of defense.

Advanced Validation with Server‑Side JavaScript

Using the sandboxed JS API

Client‑side checks are useful, but they can be bypassed. Qödiak’s JavaScript Scripting feature (available on the Starter plan and up) lets you run server‑side validation right after a user submits the form.

Open the Scripts tab for your page and add a onSubmit handler. The API gives you access to the uploaded file via getField('myFile'). Here’s a skeleton:

async function onSubmit(event) {
  const file = getField('myFile');
  // Perform custom checks
  await validateMime(file);
  await checkFileSize(file);
  // If everything passes, allow the submission
  return true;
}

Example: Validate MIME type and virus‑scan placeholder

The following script demonstrates two practical checks:

  1. Confirm the MIME type matches an allowed list.
  2. Call a mock virus‑scan endpoint (replace with a real service in production).
async function validateMime(file) {
  const allowed = ['image/jpeg', 'image/png', 'application/pdf'];
  if (!allowed.includes(file.mime)) {
    showMessage('Unsupported file type.', 'error');
    throw new Error('Invalid MIME');
  }
}

async function checkFileSize(file) { const maxBytes = 10 * 1024 * 1024; // 10 MB if (file.size > maxBytes) { showMessage('File exceeds 10 MB limit.', 'error'); throw new Error('File too large'); } }

async function virusScan(file) { // Placeholder: pretend we send the file to an external API const response = await fetch('https://example.com/scan', { method: 'POST', body: file.blob }); const result = await response.json(); if (!result.clean) { showMessage('File failed virus scan.', 'error'); throw new Error('Virus detected'); } }

async function onSubmit(event) { const file = getField('myFile'); await validateMime(file); await checkFileSize(file); await virusScan(file); return true; // continue submission }

Tip: Keep server‑side scripts lightweight. Qödiak enforces a 5‑second timeout and memory limits to protect performance.

Conditional validation based on user role

Because every Qödiak app includes built‑in authentication, you can tailor validation rules to the current user’s role. Use getSession('role') to fetch the role and adjust limits:

async function checkFileSize(file) {
  const role = getSession('role');
  const max = role === 'admin' ? 50 : 10; // MB
  const maxBytes = max * 1024 * 1024;
  if (file.size > maxBytes) {
    showMessage(`File exceeds ${max} MB limit for your role.`, 'error');
    throw new Error('File too large');
  }
}

This approach lets a marketing team upload high‑resolution assets while regular users stay within tighter bounds.

Multi‑File Uploads and Dynamic UI Feedback

Enabling multiple uploads

Toggle the Multiple Files switch in the component settings. Qödiak will automatically render a repeatable file selector, and each file is stored as a separate entry in the submission record.

Displaying progress bars and error messages

To improve the user experience, add a ProgressBar component next to the upload field. Bind its value property to the upload progress using the scripting API:

function onUploadProgress(event) {
  const percent = Math.round((event.loaded / event.total) * 100);
  setField('uploadProgress', percent);
}

// Attach the handler when the component mounts document.addEventListener('DOMContentLoaded', () => { const fileInput = getFieldComponent('myFile'); fileInput.addEventListener('progress', onUploadProgress); });

When validation fails, call showMessage() with the 'error' style; the message appears in a toast that automatically disappears after a few seconds.

Integrating Uploads with External Workflows

Triggering webhooks after successful upload

Qödiak’s Webhooks let you notify downstream systems (e.g., a document‑management platform) the moment a file passes validation. In the onSubmit script, after all checks succeed, fire a webhook:

async function onSubmit(event) {
  const file = getField('myFile');
  await validateMime(file);
  await checkFileSize(file);
  // All good – send webhook
  await fetch('https://hooks.example.com/qod-upload', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      fileName: file.name,
      mime: file.mime,
      size: file.size,
      uploadedBy: getSession('userId')
    })
  });
  return true;
}

Connect this webhook to Zapier, Make, or n8n to route the file to cloud storage, trigger approval workflows, or log the event in a CRM.

Storing files in third‑party storage via API

If you need more than the 100 MB free quota, use Qödiak’s External API Data Sources. After the upload passes validation, forward the binary to an S3 bucket or Azure Blob Storage:

async function uploadToS3(file) {
  const presignResponse = await fetch('https://api.example.com/s3-presign', {
    method: 'POST',
    body: JSON.stringify({ name: file.name, type: file.mime })
  });
  const { url, fields } = await presignResponse.json();
  const formData = new FormData();
  Object.entries(fields).forEach(([k, v]) => formData.append(k, v));
  formData.append('file', file.blob);
  await fetch(url, { method: 'POST', body: formData });
}

async function onSubmit(event) { const file = getField('myFile'); await validateMime(file); await checkFileSize(file); await uploadToS3(file); showMessage('File uploaded to secure storage.', 'success'); return false; // prevent default storage, we handled it }

Because the script runs server‑side, the file never touches the client’s browser beyond the initial upload, preserving privacy.

Conclusion: Build Secure, Scalable Upload Forms in Minutes

By combining Qödiak’s drag‑and‑drop FileUpload component with sandboxed JavaScript validation, multi‑file handling, and webhook integration, you can deliver professional‑grade upload experiences without writing a single line of backend code. Whether you’re collecting resumes, medical images, or marketing assets, the workflow stays the same:

  1. Define allowed types and size limits in the component UI.
  2. Add server‑side scripts for MIME, size, and optional virus scanning.
  3. Enhance UX with progress bars and clear error messages.
  4. Connect to external systems via webhooks or API calls for long‑term storage.

Ready to try it yourself? Open the Qödiak visual builder, add a FileUpload component, and follow the steps above. Your next secure file‑upload form is just a few clicks away.

Take action now: Build the form, test validation, and publish to a custom domain using Qödiak’s SSL‑protected hosting. Need help? Join the Qödiak community forum or explore our AI‑generated app templates for instant inspiration.

Publicaciones relacionadas