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:
It's important to note the following points:
uploadedimages.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:
Create an index.ts file in the /src/entities folder.
Add fields that match your collection fields, for example:
uploadedImageimageTitleuploaderNamesubmissionDateTimeisApprovedIn 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:
To build the logic:
Create the upload-image.ts file in the src/pages/api folder.
Import the packages:
Add constants:
Add helper functions for safe responses:
Add an HTTP endpoint:
Inside the HTTP endpoint define helper functions for JSON responses and request validation.
Elevate the insert() function from Data API:
Insert a new item after all validations pass:
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:
FileReader.fetch.