ai-kit-file-management
v0.7.3
Published
Provides convenient components for uploading and downloading files
Downloads
16
Readme
AI-KIT: File-Management
This is the frontend library for the AI-KIT module File-Management.
Use it in conjunction with the django package django-ai-kit-file-management
in order to get a functioning File-Management running in your app in no time.
Installation
You can easily install AI-KIT: File-Management via npmjs. Using npm, run
npm install ai-kit-file-management
Using yarn, run
yarn add ai-kit-file-management
Quickstart
API Reference
This module provides a few hooks, as well as some material-ui-styled components where these hooks are already put to use.
Types
Hooks
Components
FileData
This type describes the default data structure of file objects as per django-ai-kit-auth
.
It has the following fields:
id: number
database id of the file objectfile: string
URL to download the filecreator: number|null
database id of the user who uploaded the file, or null if the user was not logged in when they uploaded it.format: string
the file type in mime-type notation (e.g.image/jpeg
,audio/mpeg
,video/mp4
etc.)name: string
the filename
To use it, import it from 'ai-kit-file-management/dist/hooks/useUpload'
.
Translator
Several components use a translator function for displaying user-facing strings.
This type is defined as (key: string) => string
and will receive strings of the form
auth:Path.To.Key
, conforming with i18next.
If you don't need dynamic translation and are just interested in a different supported
language than the default (English), you can pass one of the predefined translator
functions exported by ai-kit-file-management
. Currently the only choice is en
.
If you need to translate only a few strings differently, we would advise you to inspect
the source code in order to find the correct keys and write a wrapper function around
one of the predefined translators in order to intercept the translation of those keys.
Example
import { DropZone, en } from 'ai-kit-file-management';
const customKey = 'file-management:DropZone.DragNDrop';
const customValue = 'Drop your files here, please!';
const t = (key: string) => {
if (key === customKey) return customValue;
return en(key);
};
export const CustomDropZone: FC = () => (
<DropZone translator={t} />
);
If you would like to use dynamic translations, we suggest to use i18next
and to pass your translator function t
to the respective components.
That way, the components are re-rendered whenever the language changes.
In that case, you need to provide all the translations by yourself, in the namespace file-management
.
To get started, you can copy the .json
files containing our translations from the
dist/internationalization
folder of this module.
Example
import { useTranslation } from 'react-i18next';
import { DropZone } from 'ai-kit-file-management';
...
const App: FC = () => {
const { t } = useTranslation(['file-management']);
return (
<DropZone translator={t} />
);
};
useFileChooser
This hook provides a simple way for your functional components to open a system
file chooser dialog.
Behind the scenes, an invisible <input />
element is rendered in a separate DOM branch,
and if the function returned by this hook is called, a click on that element is
simulated in order to open the browser's file chooser dialog.
Parameters
config: FileChooserConfig
, containing the following fields:onFileSelect?: (list: File[]) => void
is called when one or more files are selected from the dialogaccept?: string
specifies a filter of files, which are shown in the dialog. This string is passed to aninput
element withtype="file"
in the DOM. For the format and more background information, see the MDN Web Docsmultiple?: boolean
if this is set to true, the user can select multiple files at once.capture?: string
from the documentation: The capture attribute value is a string that specifies which camera to use for capture of image or video data, if the accept attribute indicates that the input should be of one of those types. A value of user indicates that the user-facing camera and/or microphone should be used. A value of environment specifies that the outward-facing camera and/or microphone should be used. If this attribute is missing, the user agent is free to decide on its own what to do. If the requested facing mode isn't available, the user agent may fall back to its preferred default mode.id?: string
defines the id of the invisible<input />
element used behind the scenes
Returns
openFileDialog: () => void
a function that you can call in order to open the file dialog.
If the user then selects a file, onFileSelect
is called with the selection, otherwise nothing happens.
Example
import React, { FC } from 'react';
import { useFileChooser } from 'ai-kit-file-management';
export const FileChooser: FC = () => {
const openFileDialog = useFileChooser({
onFileSelect: (list) => console.log('selected files:', list),
multiple: true,
});
return <div onClick={openFileDialog}>Choose File</div>;
};
useUpload
This hook provides a function with which you can upload a list of files
directly to the backend (provided you use django-ai-kit-file-management
).
It also sets up the objects it returns for cancellation and lets you track the
upload progress and error or cancellation status.
Parameters
config: UploadConfig<DataType =
FileData
>
containing the fields:apiUrl: string
the url to the upload endpoint on the backend. If you provide abaseURL
viarequestConfig
,apiUrl
will be appended to it to form the complete url.requestConfig?: AxiosRequestConfig
Since we use axios internally for the handling of requests, you can pass a configuration containing credentials headers etc. in order to get the call to succeed (see the axios documentation). If you useai-kit-auth
as well, you can simply pass theaxiosRequestConfig
obtained fromuseUserStore
orAuthFunctionContext
in order to add valid credentials to the upload request.maxFileSize?: number
the maximum allowed size of a single file. If the user attempts to upload a larger file, the upload will not even be attempted and an error is thrown. If no value is provided, no checks on the frontend are performed.onReady?: (data: DataType, key: string) => void
is called whenever an upload succeeds. Thedata
parameter is the result returned by the backend, and the generic typeDataType
defaults toFileData
, an interface describing the default data returned bydjango-ai-kit-file-management
. In case you provide your own file serializer there, you will need to specify the data structure in order to tell typescript about the available fields. Thekey
is an identifier for the file that was uploaded. You can compare it with thefileKey
field of theUploadFileInfo
objects returned by theupload
function.onUploadProgress?: (progress: number, key: string) => void
is called whenever the browser reports progress for an upload.progress
is a number between0
and100
inclusively, and100
means that the upload succeeded and was acknowledged by the server. Thekey
is an identifier for the file that was uploaded. You can compare it with thefileKey
field of theUploadFileInfo
objects returned by theupload
function.onError?: (error: Error, key: string) => void
is called when an error occurred during the upload of a file. Theerror
object is passed to this callback unfiltered, and can be any range of errors. You need to decide which errors to handle, and how. Thekey
is an identifier for the file that was uploaded. You can compare it with thefileKey
field of theUploadFileInfo
objects returned by theupload
function.onCancel?: (key: string) => void
is called by theonCancel
function on aUploadFileInfo
object returned by theupload
function, regardless of whether the corresponding file was uploaded successfully already or not.
Returns
upload: (fileList: File[]) => UploadFileInfo[]
This function can be called with a list of files in order to immediately upload them.
You can pass this function as config.onFileSelect
to useFileChooser
in
order to immediately upload selected files.
The return value is an array of UploadFileInfo
s, which in turn contain the following fields:
fileName: string
name of the filefileSize: string
the size of the file in bytesfileKey: string
a key to identify the file in upload events and identify them during callbacksonReady
,onUploadProgress
,onError
andonCancel
.onCancel: () => void
a function which, when called, cancels the upload (if it is still ongoing) and callsonCancel
provided with theconfig
touseUpload
.
Example
import React, { FC } from 'react';
import { useFileChooser, useUpload } from 'ai-kit-file-management';
export const QuickUpload: FC = () => {
const upload = useUpload({apiUrl: 'www.example.com/api/v1/upload/'});
const openFileDialog = useFileChooser({ onFileSelect: upload });
return <div onClick={openFileDialog}>Upload!</div>;
};
UploadBase
This component is a styled button which opens a file chooser dialog and immediately uploads the chosen files.
Props
<DataType =
FileData
>
a generic parameter defining the data structure expected from the backend when uploading a file.uploadConfig: UploadConfig<DatatType>
see parameters ofuseUpload
fileChooserConfig?: FileChooserConfig
see parameters ofuseFileChooser
Example
import React, { FC } from 'react';
import { UploadBase } from 'ai-kit-file-management';
export const Dashboard: FC = () => (
<div>
{/* ...beautiful dashboard code... */}
<UploadBase
uploadConfig={{ apiUrl: 'www.example.com/api/v1/upload/' }}
/>
{/* ...beautiful dashboard code... */}
</div>
);
DropZone
This component renders a nice drop field for files.
Props
fileChooserConfig?: FileChooserConfig
see parameters ofuseFileChooser
translator?:
Translator
a function for translating user facing strings
Example
import React, { FC } from 'react';
import { DropZone } from 'ai-kit-file-management';
export const Dashboard: FC = () => (
<div>
{/* ...beautiful dashboard code... */}
<DropZone
fileChooserConfig={{
onFileSelect: (list: File[]) => list.forEach(
(file) => console.log('file', file.name, 'was selected')),
}}
/>
{/* ...beautiful dashboard code... */}
</div>
);
FileUploadProgress
This component shows the progress of a single file, which is being uploaded,
and renders a button for cancelling the upload.
It is used by DropAndUpload
.
Props
This component requires all the fields of UploadFileInfo
(see useUpload
):
fileName: string
name of the filefileSize: string
the size of the file in bytesfileKey: string
a key to identify the file in upload eventsonCancel: () => void
a function which cancels the upload
Furthermore, it takes these additional properties:
progress?: number
represents the upload progress in percenterror?: string
is displayed instead of a progress bar, if presentnoBorder?: boolean
if true, no border is drawn around the componenttranslator?:
Translator
a function for translating user facing strings
Example
import React, { FC, useState, useEffect } from 'react';
import { FileUploadProgress, useUpload } from 'ai-kit-file-management';
import { UploadFileInfo } from 'ai-kit-file-management/dist/hooks/useUpload';
export const UploadFileList: FC = ({ files: File[] }) => {
const [progress, setProgress] = useState<UploadFileInfo[]>([]);
const handleUploadProgress = (progress: number, key: string) => {
setProgress((prev) => prev.map(
(oldProgress) => (oldProgress.fileKey !== key ? oldProgress : ({
...oldProgress,
progress,
})),
));
};
const upload = useUpload({
apiUrl: 'www.example.com/api/v1/upload/',
onUploadProgress: handleUploadProgress,
});
useEffect(() => {
setProgress(upload(files);
}, [files]);
return (
<div>
{progress.map((uploadProgress) => (
<FileUploadProgress
{ ...uploadProgress }
/>
))}
</div>
);
DropAndUpload
This component consists of a DropZone
, which immediately uploads
any files dropped into it, and optionally a list of
FileUploadProgress
es showing the status of those uploads.
Props
<DataType =
FileData
>
a generic parameter defining the data structure expected from the backend when uploading a file.showList?: boolean
whether or not to show progress of individual files (default:false
)uploadConfig: UploadConfig<DataType>
see parameters ofuseUpload
fileChooserConfig?: Omit<FileChooserConfig, 'onFileSelect'>
see parameters ofuseFileChooser
. TheonFileSelect
cannot be provided, because it is defined byDropAndUpload
itself.translator?:
Translator
a function for translating user facing strings
Example
import React, { FC } from 'react';
import { DropAndUpload } from 'ai-kit-file-management';
export const Dashboard: FC = () => (
<div>
{/* ...beautiful dashboard code... */}
<DropAndUpload
showList
uploadConfig={{
apiUrl: '/files/upload/',
}}
/>
{/* ...beautiful dashboard code... */}
</div>
);
DropAndUploadSingle
Similarly to DropAndUpload
, this component consists of a
DropZone
, which immediately uploads a file dropped into it.
However, after a file has been dropped, the DropZone
is replaced by a
FileUploadProgress
showing the status of that upload.
The use is not able to upload another file until they click the close button on the
FileUploadProgress
, cancelling the upload if it is still
ongoing. Also, the
Props
<DataType =
FileData
>
a generic parameter defining the data structure expected from the backend when uploading a file.showList?: boolean
whether or not to show progress of individual files (default:false
)uploadConfig: UploadConfig<DataType>
see parameters ofuseUpload
fileChooserConfig?: Omit<FileChooserConfig, 'onFileSelect'|'multiple'>
see parameters ofuseFileChooser
. TheonFileSelect
cannot be provided, because it is defined byDropAndUpload
itself.multiple
cannot be provided since only one file is allowed to be chosen.translator?:
Translator
A translator function for user-facing strings
Example
import React, { FC } from 'react';
import { DropAndUploadSingle } from 'ai-kit-file-management';
export const ThumbnailModalContent: FC = () => (
<div>
<DropAndUploadSingle
uploadConfig={{
apiUrl: '/files/upload/',
}}
/>
</div>
);