Skip to main content
Version: next

Handle file uploads

In this guide, you will learn how to handle file uploads.

info

You can find a complete example of file upload in the File Upload example extension

Handle file upload

File upload is a common feature in many web applications, since Front-Commerce is based on Remix, it means that you can handle file upload using action function.

tip

By default, uploaded file is stored in memory, if you need to handle large files, we recommend you to save it to external storage like S3.

If you need this kind of advanced usage, please check the unstable_parseMultipartFormData guide from Remix.

Implementation example

You first need to create a route with a Form component, and set the encType attribute to multipart/form-data.

app/routes/upload-demo.tsx
import { Form } from "@remix-run/react";

export default function UploadDemo() {
return (
<Form method="post" encType="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</Form>
);
}

Then you need to create an action function to handle the file upload.

app/routes/upload-demo.tsx
import { json } from "@front-commerce/remix/node";
import { type ActionFunctionArgs } from "@remix-run/node";

export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const file = formData.get("file") as File;
const fileContent = await file.text();
return json({ fileContent });
}
tip

Please note that here we use the .text method to get the file content as a text string.

You can use other methods from the Blob object to get the file content, for mere infos, please check the Blob documentation.