Custom File Uploads

Start of documentation content

Forms with file fields can have files uploaded to your servers.

In Formally files are immediately uploaded after the user chooses them, before the form submit. This optimises for bandwidth, and gives good UX feedback on upload progress, errors, at the point in the form where the user chose to upload files.

With the onUpload prop file uploads can be sent to your own servers.

The response should be an array of references to the files (e.g. S3 Keys, or file ids) for each uploaded file (<input type="file"> supports multiple files).

When the user submits the form those references will be submitted as form data. If those references aren't submitted it means the user chose to delete the upload. As such, any server handling submissions should should periodically 'garbage collect' any older upload files with unrecognised form references.

Use of onUpload

import { Formally } from 'formally';

<Formally
  onUpload={async ({
    inputChangeEvent,
    // Can be called multiple times to indicate upload progress.
    // Set the value between 0 and 1.
    setProgressRatio,
    abortControllerSignal, // See MDN abortControllerSignal
    uploadNode,
  }) => {
    const { files } = inputChangeEvent.target;
    if (!files) return [];

    // If you were to upload files it might look like...
    //
    // const formData = new FormData(); // See MDN FormData
    // Array.from(files).forEach((file, index) => {
    //   formData.append(`file${index}`, file);
    // });
    // const response = await fetch(`https://example.com/api/upload`, {
    //   method: 'POST',
    //   body: formData,
    // });
    // const uploadResults = await response.json();

    return ['s3Key1', 's3Key2'];
  }}
/>;