Tutorial | Upload Images to CMS

This tutorial shows you how to let site visitors upload an image to a site collection with the collection having restricted permissions for site visitors.

Note: We'll be storing image content as a data URL for simplicity. You can enhance the project by using the Media Files API.

The flow in this article uses:

The end result is an image upload function that validates input and inserts new CMS items.

We'll use the following steps to build the upload flow:

  1. Create a CMS collection for uploaded images.
  2. Build a secure backend upload route.
  3. Add a minimal frontend upload form.

Before you begin

It's important to note the following points:

  • You have a headless project setup completed.
  • You have a CMS collection named uploadedimages.

Step 1 | Create the CMS collection schema

In this step, you'll define the collection and fields in code.

At the end of this step, your uploadedimages collection will match the payload inserted by the HTTP endpoint.

To create the schema:

  1. Create an index.ts file in the /src/entities folder.

  2. Add fields that match your collection fields, for example:

    • uploadedImage
    • imageTitle
    • uploaderName
    • submissionDateTime
    • isApproved
    Copy

Step 2 | Build server logic for uploading images

In this step, you'll create an HTTP endpoint that accepts images from visitors and writes validated data to a collection.

At the end of this step, your code will:

  • Validate content type and required fields.
  • Insert an item using an elevated backend call.

To build the logic:

  1. Create the upload-image.ts file in the src/pages/api folder.

  2. Import the packages:

    Copy
  3. Add constants:

    Copy
  4. Add helper functions for safe responses:

    Copy
  5. Add an HTTP endpoint:

    Copy
  6. Inside the HTTP endpoint define helper functions for JSON responses and request validation.

    Copy
  7. Elevate the insert() function from Data API:

    Copy
  8. Insert a new item after all validations pass:

    Copy

Step 3 | Add a minimal frontend upload form

In this step, you'll create a small form component that converts a selected file into a data URL and sends it to your backend.

To add the frontend form:

  1. Create a page component.
  2. Add inputs for file, title, and uploader name.
  3. Convert the file to a base64 data URL with FileReader.
  4. Call you backend endpoint with fetch.

Full backend code

Copy

Full frontend code

Copy

See also

Did this help?