Documentation
Guides and API reference for uploads, image transforms and video.
npm install @cd2/fileboy-react API https://api.fileboy.io
Documentation menu
React integration
The React package allows you to easily insert a file uploader into your app in minutes.
Installation and usage
The easiest way to use fileboy-react is to install it from npm.
1 2 3 4 5yarn add @cd2/fileboy-react # or npm install @cd2/fileboy-react
With Fileboy installed, you should use the FileboyProvider to wrap your application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16import React from "react" import ReactDom from "react-dom" import { FileboyProvider } from "@cd2/fileboy-react" function App() { return ( <FileboyProvider publicKey={YOUR_PUBLIC_KEY}> <div> <h1>My application</h1> </div> </FileboyProvider> ) } ReactDom.render(<App />, document.getElementById("root"))
The provider requires you to pass your public key as this will be used by us to know which application uploaded files belong to:
Provider
<FileboyProvider />The provider should wrap all of your application that uses any other Fileboy component.
Props
publicKey string
The public key for your Fileboy app
namespace string, optional
Optionally specify a name for the provider. Allows nesting multiple Fileboy providers in a single app.
fetchMethod {
method: "GET" | "POST"
url: string
headers?: Record<string, string>
body?: string | FormData
}) => Promise<[number, any]>, optional
Override the default fetch method - useful when testing
uploadToken string | () => Promise<string>, optional
Have the uploaders get a short-lived upload token before each upload, so your server decides who uploads and their files are signed (signed: true; the public key alone still uploads unsigned files, so check signed on your server to keep only these): the URL of an endpoint on your server that answers { "token": "..." } (POSTed to with the page's cookies), or a function. Make it with createUploadTokenHandler from @cd2/fileboy-next, or createAccessToken({ upload: true }) from the Node library.
transformUrl (url: string) => string, optional
Rewrite every file and image URL, for example to sign it for an app that requires signed reads.
children React.ReactNode
Children
1 2 3 4 5 6 7 8 9import { FileboyProvider } from "@cd2/fileboy-react" function App() { return ( <FileboyProvider publicKey={YOUR_PUBLIC_KEY}> <h1>App</h1> </FileboyProvider> ) }
useFileboy
const client = useFileboy()The useFileboy hook returns a Fileboy client that is bound with your public key. It must be used in a component tree that is wrapped with a FileboyProvider.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19import { useFileboy } from "@cd2/fileboy-react" function Component() { const { buildFileUrl, buildImageUrl, getFileData, getFilePalette, searchFileData, uploadFile, uploadFileFromUrl, } = useFileboy() return ( <div> <h1>Component</h1> </div> ) }
The client returned offers several functions for building urls for files, getting data for a file and uploading new files.
Client
buildFileUrl (id: string, options?: IFileUrlOptions) => Promise<string>
Build a public URL for a file. You can also provide a single argument of an IFileUrlOptions object containing an additional property of id or label.
IFileUrlOptions
filename string, optional
Override the saved filename. This may still have an extension appended to it.
download boolean, optional
Whether following this link should download the file, rather than opening it.
buildImageUrl (id: string, options?: IImageUrlOptions) => Promise<string>
Build a public URL for an image. The image can be converted and transformed on the fly. You can also provide a single argument of an IImageUrlOptions object containing an additional property of id or label.
IImageUrlOptions
filename string, optional
Override the saved filename. This may still have an extension appended to it.
download boolean, optional
Whether following this link should download the image, rather than opening it.
transformations array of transform objects, optional
Transformations to apply to the image. For a list of transformation options see the transformation section of the docs.
getFilePalette (id: string, options?: { colors?: number }) => Promise<IPalette>
Fetch an image's colour palette: the dominant colour, up to 16 main colours with their share of the image, named swatches and a readable text colour for each. It reads the palette transform, so it follows the image's read access.
searchFileData (filter: { metadata: IMetaData } | { hash: string }) => Promise<IFileData[]>
Fetch a filtered list of files, either by their SHA1 hash or their metadata content.
uploadFile (file: File, options?: IFileUploadOptions) => Promise<IFileData>
Upload a new file.
IFileUploadOptions
name string, optional
Specify the name of the file.
mime string, optional
Specify a custom mime.
metadata IMetaData, optional
Custom data to be saved with the file.
folderId string, optional
Put the file in this folder.
folderPath string, optional
Put the file in the folder at this path, like "/uploads/avatars". With the public key the folder must already exist.
uploadVideo (file: Blob, options?) => Promise<IUploadedVideo>
Upload a video or audio file with the public key. options: name, mime, description, tags, metadata, accessToken, onProgress and resumable. Posters and captions need the private key: add them from your server with the Node library.
uploadFileFromUrl (url: string, options?: IFileUploadOptions) => Promise<IFileData>
Upload a new file from a remote URL
IFileUploadOptions
name string, optional
Specify the name of the file.
mime string, optional
Specify a custom mime.
metadata IMetaData, optional
Custom data to be saved with the file.
folderId string, optional
Put the file in this folder.
folderPath string, optional
Put the file in the folder at this path, like "/uploads/avatars". With the public key the folder must already exist.
expect string or string[], optional
Expected mime type to be returned from the URL. The upload will fail if the response does not match it.
You can optionally pass a namespace argument to the hook to consume a specific context if you have configured multiple providers in your app.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23import { FileboyProvider, useFileboy } from "@cd2/fileboy-react" const namespace = "myNamespace" function App() { return ( <FileboyProvider publicKey={YOUR_OTHER_PUBLIC_KEY}> <FileboyProvider publicKey={YOUR_PUBLIC_KEY} namespace={namespace}> <Component /> </FileboyProvider> </FileboyProvider> ) } function Component() { const client = useFileboy(namespace) return ( <div> <h1>Component</h1> </div> ) }
Image
<Image />The image component takes an id for an image and will build a public url for it and will then render an img tag to display it.
1 2 3 4 5 6 7 8 9 10 11 12import { Image } from "@cd2/fileboy-react" function Component() { const myImageId = "00000000-0000-0000-0000-000000000002" return ( <div> <h1>Image</h1> <Image id={myImageId} /> </div> ) }
The img tag can be styled using the className prop and it also takes transformation options so you can manipulate the image.
Props
id string
label string
className string, optional
A class name to directly style the img tag
onError (event: React.SyntheticEvent<HTMLImageElement, Event>) => void, optional
Function that is called when the image fails to load
onClick (event: MouseEvent<HTMLDivElement, MouseEvent>) => void, optional
A click handler for the generated element. Can be triggered before the file has loaded.
format "jpeg" | "png" | "webp" | "tiff", optional
Convert the image to a different format.
namespace string, optional
Optionally specify which fileboy context to access, if you have multiple.
transforms array of transform objects, optional
Transformations to apply to the image. For a list of transformation options see the transformation section of the docs.
preset string, optional
A transform preset your app has saved, run before transforms. See Transform presets.
widths number[] | true, optional
Adds a srcset with one URL per width (true for 320, 640, 960, 1280 and 1920): the preset and transforms, then a resize to that width that never makes the image bigger than its source. For example <Image id={id} preset="card" widths={[320, 640, 1280]} sizes="(max-width: 640px) 100vw, 640px" />.
sizes string, optional
The img sizes attribute, used with widths.
placeholderColor string | "auto", optional
A colour shown behind the image until it has loaded, then taken away so it never shows through transparent parts. Pass the dominantColor your server got from the management API so it shows at once, or "auto" to fetch the image's palette first. See Colour palettes.
imgProps object of <img> attributes (alt, width, height, loading...) except src, srcSet, sizes, className, onError and onLoad, optional
Allows passing through html image element props directly to the underlying img element
File Preview
<FilePreview />The file preview component takes an id and, depending on the file the id corresponds to, it will display an image or a FileIcon.
1 2 3 4 5 6 7 8 9 10 11 12import { FilePreview } from "@cd2/fileboy-react" function Component() { const myFileId = "00000000-0000-0000-0000-000000000001" return ( <div> <h1>Preview</h1> <FilePreview id={myFileId} /> </div> ) }
Props
id string
label string
height number, optional
Specify the height of the preview in px. Defaults to 125px.
width number, optional
Specify the width of the preview in px. Defaults to 125px.
onClick (event: MouseEvent<HTMLDivElement, MouseEvent>) => void, optional
A click handler for the generated element. Can be triggered before the file has loaded.
namespace string, optional
Optionally specify which fileboy context to access, if you have multiple.
File Icon
<FileIcon />Displays a coloured file icon SVG, including the extension if given.
1 2 3 4 5 6 7 8 9 10import { FileIcon } from "@cd2/fileboy-react" function Component() { return ( <div> <h1>Icon</h1> <FileIcon extension="jpg" /> </div> ) }
Props
extension string, optional
File extension to display on the icon.
error boolean, optional
Display the error variation of the icon.
width number, optional
Specify the width of the SVG in px.
height number, optional
Specify the height of the SVG in px.
File Uploader
<FileboyUploader />The React implementation of the Fileboy uploader, a simple implementation looks like:
1<FileUploader fileId={form.fileId} onFileUploaded={handleFieldChange} />
There are many props to customise the file uploader.
Props
onUploadStart () => void, optional
Function called when the upload begins
onUploadEnd () => void, optional
Function called when the upload ends
onRemoveFile (id: string) => void, optional
Function called when the file is removed. When passing this prop - remove buttons are present with the file previews.
onFileUploaded (data: IFileData) => void
Function called when the upload has complete
IFileData
id string
Unique file id.
name string
File name.
mime string
Mime type of the file, eg. 'image/png'.
metadata IMetaData
Custom data provided with the upload.
fileSize number
Size of the file in bytes.
hash string
SHA1 hash of the file's contents.
signed boolean
Whether the file was uploaded using a signed request.
diesAt Date | null
Timestamp when the file will be automatically deleted.
createdAt Date
Timestamp when the file was created.
theme IUploaderRendererThemeProps, optional
Theme options for the uploader
IUploaderRendererThemeProps
colors {
button?: string
buttonText?: string
}, optional
Colors of the button and or button text
fontFamily string, optional
Override the default font family
allow string, string[], optional
One or more allow types for files
defaultFileId string, optional
Pass in a Fileboy id to the component to see a preview on render
render (opts: ISingleUploaderRendererProps) => JSX.Element, optional
Override the default File uploader with a custom implementation, see the section on custom file uploaders
fileName (opts: { file: File; rawName: string; ext?: string; baseName: string }) => string, optional
A function that returns the filename for the file being uploaded
metadata (opts: { file: File; rawName: string; ext?: string; baseName: string }) => IMetaData, optional
A function that returns the metadata for the file being uploaded
folderId string, optional
Upload into this folder.
folderPath string, optional
Upload into the folder at this path. It must already exist: create it from your server.
uploaderStyle "minimal" | "buttonOnly" | "default", optional
Choose the style of the uploader
paste boolean, optional
Upload files pasted anywhere on the page, like a screenshot (named with the time it was pasted). Text pastes are left alone. Turn it on for one uploader per page.
capture "user" | "environment" | boolean, optional
On phones, open the camera instead of the file picker: "environment" is the back camera, "user" the front one. Desktop browsers show the file picker.
urlImport boolean, optional
Show a field to import a file from a link. Fileboy fetches it, so it must be public: links to localhost and private or cloud metadata addresses are refused, in the browser and by the API. A render prop gets uploadUrlManually(url) to build your own.
uploadToken string | () => Promise<string>, optional
Get a short-lived upload token before each upload, overriding the provider's. See the provider's uploadToken.
namespace string, optional
Optionally specify which fileboy context to access, if you have multiple.
Multiple File Uploader
<MultiFileUploader />A Fileboy uploader that allows you handle multiple uploads at once. A simple implementation looks like:
1<MultiFileUploader onFilesUploaded={handleFieldChange} />
There are many props to customise the multiple file uploader.
Props
onStartUpload () => void, optional
Function called when the upload begins
onUploadEnd () => void, optional
Function called when the upload ends
onFileRemove (id: string) => void, optional
Function called when the file is removed. When passing this prop - remove buttons are present with the file previews.
onFilesUploaded (data: IFileData[]) => void
Function called when the upload has completed for all files
IFileData
id string
Unique file id.
name string
File name.
originalFilename string
The name of the file when it was uploaded, if available
mime string
Mime type of the file, eg. 'image/png'.
metadata IMetaData
Custom data provided with the upload.
fileSize number
Size of the file in bytes.
hash string
SHA1 hash of the file's contents.
signed boolean
Whether the file was uploaded using a signed request.
diesAt Date | null
Timestamp when the file will be automatically deleted.
createdAt Date
Timestamp when the file was created.
theme IUploaderRendererThemeProps, optional
Theme options for the uploader
IUploaderRendererThemeProps
colors {
button?: string
buttonText?: string
}, optional
Colors of the button and or button text
fontFamily string, optional
Override the default font family
allow string, string[], optional
One or more allow types for files
defaultFileIds string[], optional
Pass in an array of Fileboy ids to the component to see a preview on render
render (opts: IMultiUploaderRendererProps) => JSX.Element, optional
Override the default File uploader with a custom implementation, see the section on custom file uploaders
fileName (opts: { file: File; rawName: string; ext?: string; baseName: string; index: number }) => string, optional
A function that returns the filename for the file being uploaded
metadata (opts: { file: File; rawName: string; ext?: string; baseName: string; index: number }) => IMetaData, optional
A function that returns the metadata for the file being uploaded
folderId string, optional
Upload into this folder.
folderPath string, optional
Upload into the folder at this path. It must already exist: create it from your server.
uploaderStyle "minimal" | "buttonOnly" | "default", optional
Choose the style of the uploader
paste boolean, optional
Upload files pasted anywhere on the page, like a screenshot (named with the time it was pasted). Text pastes are left alone. Turn it on for one uploader per page.
capture "user" | "environment" | boolean, optional
On phones, open the camera instead of the file picker: "environment" is the back camera, "user" the front one. Desktop browsers show the file picker.
urlImport boolean, optional
Show a field to import a file from a link. Fileboy fetches it, so it must be public: links to localhost and private or cloud metadata addresses are refused, in the browser and by the API. A render prop gets uploadUrlManually(url) to build your own.
uploadToken string | () => Promise<string>, optional
Get a short-lived upload token before each upload, overriding the provider's. See the provider's uploadToken.
namespace string, optional
Optionally specify which fileboy context to access, if you have multiple.
File Data
<FileData />This component takes a file id and will look up its data and then pass that down to the children. The simplest implementation looks like:
1 2 3<FileData id={myFileBoyId}> {file => <div>Name: {file.name}</div>} </FileData>
The component can be customised by passing in a custom loading function or it can be configured to always display the children while it is loading the file data. If it fails to load the data, it will return an error key.
Props
id string
label string
renderLoading () => React.ReactNode, optional
An alternative function to call on renders when the file data has not yet been fetched.
renderChildrenWhileLoading boolean, optional
Call the child function on every render, even before the file data has been fetched.
namespace string, optional
Optionally specify which fileboy context to access, if you have multiple.
children (data: IFileData | { id: string; error: true }) => React.ReactNode
Child function that receives the file data
IFileData
id string
Unique file id.
name string
File name.
mime string
Mime type of the file, eg. 'image/png'.
metadata IMetaData
Custom data provided with the upload.
fileSize number
Size of the file in bytes.
hash string
SHA1 hash of the file's contents.
signed boolean
Whether the file was uploaded using a signed request.
diesAt Date | null
Timestamp when the file will be automatically deleted.
createdAt Date
Timestamp when the file was created.
Video player
<fileboy-player>Video plays in the @cd2/fileboy-player web component, which works in React like any other element. Import it once and give it a video id. It plays the adaptive stream with a poster, quality, speed and captions menus.
1npm install @cd2/fileboy-player
1 2 3import "@cd2/fileboy-player" <fileboy-player video-id="YOUR_VIDEO_ID" />
See Play a video for its attributes, events and how to use them from React 16 to 18, and Video for how uploads are processed.