ai-kit-file-management v0.7.3
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-managementUsing yarn, run
yarn add ai-kit-file-managementQuickstart
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: numberdatabase id of the file objectfile: stringURL to download the filecreator: number|nulldatabase id of the user who uploaded the file, or null if the user was not logged in when they uploaded it.format: stringthe file type in mime-type notation (e.g.image/jpeg,audio/mpeg,video/mp4etc.)name: stringthe 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[]) => voidis called when one or more files are selected from the dialogaccept?: stringspecifies a filter of files, which are shown in the dialog. This string is passed to aninputelement withtype="file"in the DOM. For the format and more background information, see the MDN Web Docsmultiple?: booleanif this is set to true, the user can select multiple files at once.capture?: stringfrom 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?: stringdefines 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: stringthe url to the upload endpoint on the backend. If you provide abaseURLviarequestConfig,apiUrlwill be appended to it to form the complete url.requestConfig?: AxiosRequestConfigSince 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-authas well, you can simply pass theaxiosRequestConfigobtained fromuseUserStoreorAuthFunctionContextin order to add valid credentials to the upload request.maxFileSize?: numberthe 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) => voidis called whenever an upload succeeds. Thedataparameter is the result returned by the backend, and the generic typeDataTypedefaults 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. Thekeyis an identifier for the file that was uploaded. You can compare it with thefileKeyfield of theUploadFileInfoobjects returned by theuploadfunction.onUploadProgress?: (progress: number, key: string) => voidis called whenever the browser reports progress for an upload.progressis a number between0and100inclusively, and100means that the upload succeeded and was acknowledged by the server. Thekeyis an identifier for the file that was uploaded. You can compare it with thefileKeyfield of theUploadFileInfoobjects returned by theuploadfunction.onError?: (error: Error, key: string) => voidis called when an error occurred during the upload of a file. Theerrorobject is passed to this callback unfiltered, and can be any range of errors. You need to decide which errors to handle, and how. Thekeyis an identifier for the file that was uploaded. You can compare it with thefileKeyfield of theUploadFileInfoobjects returned by theuploadfunction.onCancel?: (key: string) => voidis called by theonCancelfunction on aUploadFileInfoobject returned by theuploadfunction, 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 UploadFileInfos, which in turn contain the following fields:
fileName: stringname of the filefileSize: stringthe size of the file in bytesfileKey: stringa key to identify the file in upload events and identify them during callbacksonReady,onUploadProgress,onErrorandonCancel.onCancel: () => voida function which, when called, cancels the upload (if it is still ongoing) and callsonCancelprovided with theconfigtouseUpload.
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 ofuseUploadfileChooserConfig?: FileChooserConfigsee 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?: FileChooserConfigsee parameters ofuseFileChoosertranslator?:Translatora 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: stringname of the filefileSize: stringthe size of the file in bytesfileKey: stringa key to identify the file in upload eventsonCancel: () => voida function which cancels the upload
Furthermore, it takes these additional properties:
progress?: numberrepresents the upload progress in percenterror?: stringis displayed instead of a progress bar, if presentnoBorder?: booleanif true, no border is drawn around the componenttranslator?:Translatora 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
FileUploadProgresses 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?: booleanwhether or not to show progress of individual files (default:false)uploadConfig: UploadConfig<DataType>see parameters ofuseUploadfileChooserConfig?: Omit<FileChooserConfig, 'onFileSelect'>see parameters ofuseFileChooser. TheonFileSelectcannot be provided, because it is defined byDropAndUploaditself.translator?:Translatora 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?: booleanwhether or not to show progress of individual files (default:false)uploadConfig: UploadConfig<DataType>see parameters ofuseUploadfileChooserConfig?: Omit<FileChooserConfig, 'onFileSelect'|'multiple'>see parameters ofuseFileChooser. TheonFileSelectcannot be provided, because it is defined byDropAndUploaditself.multiplecannot be provided since only one file is allowed to be chosen.translator?:TranslatorA 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>
);