Import
import { Upload } from '@dnb/eufemia'
Description
The Upload component should be used in scenarios where the user has to upload any kind of files.
How to use the Upload component
- Files selected by the user should be uploaded immediately (temporary location).
- The user should be able to remove them (files) during the session.
- The Upload component connects to the GlobalStatus and displays file error messages there as well.
- Validation messages coming from the "backend" should be displayed for each file via the
useUpload
hook. See example below. - The
useUpload
hook can be placed on any location in your application, and does not need to be where theUpload
component is used.
function YourComponent() {const { files, setFiles } = Upload.useUpload('unique-id')React.useEffect(() => {setFiles(files.map((fileItem) => {if (fileItem.file.name === fileNameFromBackend) {fileItem.errorMessage = 'Your message from the backend'}return fileItem}),)}, [fileNameFromBackend])return <Upload id="unique-id" />}
JPG vs JPEG
When jpg
is defined (most commonly used), then the component will also accept jpeg
files.
Backend integration
The "backend" receiving the files is decoupled and can be any existing or new system.
Limit the amount of files
By default, the Upload component accepts multiple files. You can use the property filesAmountLimit={1}
to make the component accept only one file.
Page wide drop support
Once the Upload component mounts, it also adds support for dropping files to the entire browser body.
NB: When you have several mounted components, only the first Upload component will receive the dropped files.
download
property
The Each file item is displayed as a clickable link with its original file name, which opens the file source in a new browser tab.
In some situations, it's more suitable to have each link download the file instead of opening it in a new browser tab. To achieve this, set the download={true}
property on the Upload component.
Demos
Upload (default)
Last opp dokumenter
Dra og slipp eller velg hvilke filer du vil laste opp.
- Tillatte filformater:
- JPG, PNG
- Maks filstørrelse:
- 5 MB
<Upload acceptedFileTypes={['jpg', 'png']} id="upload-basic" />
useUpload
React Hook
By using the Upload.useUpload
you can remove or add files or the status displayed in the component.
You can also use the file blob in combination with the FileReader API.
Last opp dokumenter
Dra og slipp eller velg hvilke filer du vil laste opp.
- Tillatte filformater:
- JPG, PNG
- Maks filstørrelse:
- 5 MB
const Component = () => { const { files, setFiles } = Upload.useUpload('upload-remove-files') return ( <> <Upload acceptedFileTypes={['jpg', 'png']} id="upload-remove-files" /> <Button top="small" disabled={files.length < 1} onClick={() => setFiles([])} > Remove selected files </Button> <Preview files={files} /> </> ) function Preview({ files }) { const [images, setImages] = React.useState([]) React.useEffect(() => { files.map(({ file }) => { let reader = new FileReader() reader.addEventListener( 'load', (event) => { images.push({ blob: event.target, file, }) setImages([...images]) reader = null }, false, ) reader.readAsDataURL(file) }) }, [files]) return ( <Section aria-label="List of chosen images"> {images.map((img, i) => ( <Img top key={i} src={img.blob.result} alt={img.file.name} height={100} /> ))} </Section> ) } } render(<Component />)
Upload single file/fixed amount of files
Last opp dokumenter
Dra og slipp eller velg hvilken fil du vil laste opp.
- Tillatte filformater:
- JPG, PNG
- Maks filstørrelse:
- 5 MB
- Maks antall filer:
- 1
const Component = () => { const { files, setFiles } = Upload.useUpload('upload-single-file') if (files.length) { console.log('files', files, setFiles) } return ( <Upload acceptedFileTypes={['jpg', 'png']} id="upload-single-file" filesAmountLimit={1} /> ) } render(<Component />)
Upload loading state
When uploading the file you can set the loading state of the request using the Upload.useUpload
hook and passing isLoading
to the file that is being uploaded.
Last opp dokumenter
Dra og slipp eller velg hvilke filer du vil laste opp.
- Tillatte filformater:
- JPG, PNG
- Maks filstørrelse:
- 5 MB
const Component = () => { const { files, setFiles } = Upload.useUpload('upload-is-loading') React.useEffect(() => { setFiles([ { file: createMockFile('fileName.png', 123, 'image/png'), isLoading: true, }, ]) }, []) return ( <> <Upload acceptedFileTypes={['jpg', 'png']} id="upload-is-loading" /> <ToggleButton top="small" disabled={files.length < 1} on_change={({ checked }) => setFiles( files.map((fileItem) => { return { ...fileItem, isLoading: checked, } }), ) } > Files is loading toggle </ToggleButton> </> ) } render(<Component />)
Upload error message
The only file verification the Upload component does is for the file size and the file type. These errors are handled by the HTML element input
so they aren't selectable. If you want any other error messages you can use the Upload.useUpload
hook the same way as with the loading state.
Last opp dokumenter
Dra og slipp eller velg hvilke filer du vil laste opp.
- Tillatte filformater:
- JPG, PNG
- Maks filstørrelse:
- 5 MB
const Component = () => { const { files, setFiles } = Upload.useUpload('upload-error-message') return ( <> <Upload acceptedFileTypes={['jpg', 'png']} id="upload-error-message" /> <ToggleButton top="small" disabled={files.length < 1} on_change={({ checked }) => { setFiles( files.map((fileItem) => { return { ...fileItem, errorMessage: checked ? 'custom error message' : null, } }), ) }} > Toggle error message </ToggleButton> </> ) } render(<Component />)
Upload specific accepted file formats
You can pass the file formats as a string array. This will restrict which files that can be selected.
Last opp dokumenter
Dra og slipp eller velg hvilke filer du vil laste opp.
- Tillatte filformater:
- JPG, PDF, PNG
- Maks filstørrelse:
- 5 MB
const Component = () => { const { files, setFiles } = Upload.useUpload('upload-accepted-formats') if (files.length) { console.log('files', files, setFiles) } return ( <Upload acceptedFileTypes={['png', 'jpg', 'pdf']} id="upload-accepted-formats" /> ) } render(<Component />)
Upload with prefilled error
Last opp dokumenter
Dra og slipp eller velg hvilke filer du vil laste opp.
- Tillatte filformater:
- JPG, PNG
- Maks filstørrelse:
- 5 MB
const Component = () => { const { files, setFiles } = Upload.useUpload('file-list') if (files.length) { console.log('files', files) } React.useEffect(() => { setFiles([ { file: createMockFile('fileName.png', 123, 'image/png'), errorMessage: 'This is no real file!', }, ]) }, []) return <Upload acceptedFileTypes={['jpg', 'png']} id="file-list" /> } render(<Component />)
Upload with file max size based on file type
The table of accepted file types is sorted descending by maxFileSize
. Multiple fileType
for the same maxFileSize
is sorted alphabetically ascending by fileType
.
Last opp dokumenter
Dra og slipp eller velg hvilke filer du vil laste opp.
Tillatte filformater: | Maks filstørrelse: |
---|---|
ODT, PDF, ZIP | 99 MB |
XLS, XLSX | 7 MB |
HTM, HTML | 6 MB |
TIF, TIFF | 5 MB |
DOC, DOCX | 4 MB |
DOC, GIF, JPG, SVG | 1 MB |
TEXT, TXT |
To disable maxFileSize
Use either 0
or false
. If maxFileSize
is not provided, it defaults to the value of Uploads fileMaxSize
which defaults to 5 MB.
Last opp dokumenter
Dra og slipp eller velg hvilke filer du vil laste opp.
Tillatte filformater: | Maks filstørrelse: |
---|---|
SVG | 5 MB |
DOC, JPG |
<Upload id="upload-file-max-size-based-on-file-format-disabled" acceptedFileTypes={[ { fileType: 'jpg', fileMaxSize: 0, }, { fileType: 'doc', fileMaxSize: false, }, { fileType: 'svg', }, ]} />
Upload without file max size
You can disable the file max size, which will deactivate all file size verifications in the Upload component. This can also be used to manually implement more complex file max size verifications.
Last opp dokumenter
Dra og slipp eller velg hvilke filer du vil laste opp.
- Tillatte filformater:
- JPG, PDF
<Upload acceptedFileTypes={['jpg', 'pdf']} id="upload-disabled-file-max-size" fileMaxSize={false} />
Upload without title and text
- Tillatte filformater:
- JPG, PNG
- Maks filstørrelse:
- 5 MB
<Upload title={false} text={false} acceptedFileTypes={['jpg', 'png']} id="upload-no-title-no-text" />
onFileDelete
Upload with async Last opp dokumenter
Dra og slipp eller velg hvilke filer du vil laste opp.
- Tillatte filformater:
- JPG, PNG
- Maks filstørrelse:
- 5 MB
async function mockAsyncFileRemoval({ fileItem }) { const request = createRequest() console.log('making API request to remove: ' + fileItem.file.name) await request(3000) // Simulate a request const mockResponse = { successful_removal: Math.random() < 0.5, // Randomly fails to remove the file } if (!mockResponse.successful_removal) { throw new Error('Unable to remove this file') } } render( <Upload onFileDelete={mockAsyncFileRemoval} acceptedFileTypes={['jpg', 'png']} id="upload-on-file-delete" />, )
onFileClick
Upload with Last opp dokumenter
Dra og slipp eller velg hvilke filer du vil laste opp.
- Tillatte filformater:
- JPG, PNG
- Maks filstørrelse:
- 5 MB
const Component = () => { const { setFiles } = Upload.useUpload('upload-on-file-click') React.useEffect(() => { setFiles([ { file: createMockFile('1501870.jpg', 123, 'image/png'), }, ]) }, []) async function mockAsyncFileFetching({ fileItem }) { const request = createRequest() console.log( 'making API request to fetch the url of the file: ' + fileItem.file.name, ) await request(2000) // Simulate a request window.open( 'https://eufemia.dnb.no/images/avatars/' + fileItem.file.name, '_blank', ) } return ( <> <Upload acceptedFileTypes={['jpg', 'png']} id="upload-on-file-click" onFileClick={mockAsyncFileFetching} /> </> ) } render(<Component />)