Skip to content

Import

import { Field } from '@dnb/eufemia/extensions/forms'
render(<Field.Upload />)

Description

Field.Upload is a wrapper for the Upload component to make it easier to use inside a form.

There is a corresponding Value.Upload component.

Relevant links

The data and file format

The returned data is an array of objects containing a file object, a unique ID, etc. The file item object contains the file itself and some additional properties like a unique ID.

{
id: '1234',
file: {
name: 'file1.jpg',
size: 1234,
type: 'image/jpeg',
},
// optional properties
exists: true,
isLoading: true,
errorMessage: 'error message',
description: 'description',
removeDeleteButton: true,
}

This data format will be returned by the onChange and the onSubmit event handlers.

Validation

The required property will validate if there are valid files present. If there are files with an error, the validation will fail.

If there are invalid files, the onSubmit event will not be called and a validation error will be shown.

Handling validation errors

Files are automatically validated for file size and file type based on the fileMaxSize and acceptedFileTypes properties. When files fail these validations, they receive an errorMessage property.

You can customize how these invalid files are displayed using the onValidationError callback:

<Field.Upload
fileMaxSize={5}
onValidationError={(invalidFiles) => {
return invalidFiles.map((file) => ({
...file,
removeLink: true, // Remove download link
removeDeleteButton: true, // Remove delete button
description: 'Cannot be uploaded due to validation error',
}))
}}
/>

How it works: The component splits newly uploaded files into two groups based on the presence of an errorMessage property:

  • Files with errorMessage → sent to onValidationError (if defined)
  • Files without errorMessage → sent to fileHandler (if defined)

The errorMessage is typically set by built-in validation (file size or file type checks), but can also be set manually. The two callbacks are mutually exclusive and only process newly added files.

Important: If fileHandler returns a file with an errorMessage, that file is already in the upload list and won't trigger onValidationError again. Handle errors from fileHandler within the fileHandler function itself by returning files with the errorMessage property set.

The onChange event handler will return an array with file item objects containing the file object and some additional properties – regardless of the validity of the file.

For error handling of invalid files, you can refer to the Upload component for more details.

Here is an example of how to use the fileHandler property to validate file sizes.

About the value and path property

The path property represents an array with an object described above:

render(
<Form.Handler defaultData={{ myFiles: files }}>
<Field.Upload path="/myFiles" />
</Form.Handler>
)

The value property represents an array with an object described above:

render(<Field.Upload value={files} />)

About the fileHandler property

The fileHandler is a handler function that supports both asynchronous and synchronous operations. It receives only newly added valid files as a parameter and returns the processed files (or a Promise when asynchronous).

Which files are passed to the handler?

  • Only newly added files: Files that were just uploaded by the user.
  • Only valid files: Files that do not have validation errors such as file size and file type (files with errorMessage are excluded).
  • Not existing files: Files that were previously uploaded and already exist in the list are not included.

What should be returned?

Return an array of file item objects with the same or modified properties:

  • Set a new id: Typically from a server response after uploading (e.g., id: data.server_generated_id).
  • Add errorMessage: To indicate upload failure and display an error message next to the file.
  • Modify other properties: Such as description, removeDeleteButton, removeLink, etc.

Automatic loading state handling

The component automatically handles asynchronous loading states during the upload process, displaying a spinner next to each file while the fileHandler is processing.

async function virusCheck(newFiles) {
const promises = newFiles.map(async (file) => {
const formData = new FormData()
formData.append('file', file.file, file.file.name)
return await fetch('/', { method: 'POST', body: formData })
.then((response) => {
if (response.ok) return response.json()
throw new Error('Unable to upload this file')
})
.then((data) => {
return {
...file,
id: data.server_generated_id,
}
})
.catch((error) => {
return {
...file,
errorMessage: error.message,
}
})
})
return await Promise.all(promises)
}

TransformIn and TransformOut

You can use the transformIn and transformOut properties to transform the data from the internal format to the external format and vice versa.

import { Form, Field, Tools } from '@dnb/eufemia/extensions/forms'
import type {
UploadValue,
UploadFileNative,
} from '@dnb/eufemia/extensions/forms/Field/Upload'
// Our external format
type DocumentMetadata = {
id: string
fileName: string
}
const defaultValue = [
{
id: '1234',
fileName: 'myFile.pdf',
},
] satisfies DocumentMetadata[] as unknown as UploadValue
const filesCache = new Map<string, File>()
// To the Field (from e.g. defaultValue)
const transformIn = (external?: DocumentMetadata[]) => {
return (
external?.map(({ id, fileName }) => {
const file: File =
filesCache.get(id) ||
new File([], fileName, { type: 'images/png' })
return { id, file }
}) || []
)
}
// From the Field (internal value) to the data context or event parameter
const transformOut = (internal?: UploadValue) => {
return (
internal?.map(({ id, file }) => {
if (!filesCache.has(id)) {
filesCache.set(id, file)
}
return { id, fileName: file.name }
}) || []
)
}
function MyForm() {
return (
<Form.Handler>
<Field.Upload
path="/documents"
transformIn={transformIn}
transformOut={transformOut}
defaultValue={defaultValue}
/>
<Tools.Log />
</Form.Handler>
)
}

TransformIn considerations

The properties of the file item object is used internally to visually customize the file when displayed. For instance when displaying a spinner when isLoading: true. It does also exist some internal logic based on these values, so be careful when changing these through transformers, like transformIn, as changing or overriding these properties could have unexpected results. If doing so, it's recommended to pass along the rest of the file item object using the spread operator (...fileItemObj) or so, as it can contain properties needed internally that one is not aware of, or updated values since last file was uploaded, or even future new internal properties that does not exist yet.

<Form.Handler>
<Field.Upload
path="/documents"
transformIn={(value) => {
return (value || []).map((fileItemObj) => ({
...fileItemObj,
errorMessage: 'error message',
}))
}}
/>
</Form.Handler>

Persist files in session storage

The sessionStorageId property can be used to store the files in the session storage so they persist between page reloads.

But the persisted files only render the file name, and not the file itself. The file blob will be lost during the serialization process.