Skip to content

Options ​

Pass options to the constructor, and change them later with setOption(name, value). The core options come from @vedratech/anydrop-core; the UI options (and the texts) only exist in @vedratech/anydrop-ui, which accepts every core option as well.

A function option runs with this set to the instance. The full TypeScript definitions are generated from the source: AnyDropCoreOptions and AnyDropUIOptions.

ts
import { AnyDrop } from '@vedratech/anydrop-ui';

const ad = new AnyDrop('#uploader', {
  url: '/upload',
  chunking: true,
  maxFilesize: 2048, // MiB
  acceptedFiles: 'image/*,.pdf',
});

ad.setOption('maxFiles', 10); // change it at runtime

Jump to: Request and queue / Chunking / Validation / Folders / Pause, resume and persistence / Connectivity / UI / Texts / Event handlers as options

Request and queue ​

OptionTypeDefaultDescription
urlstring | (files, dataBlocks) => string | nullnullUpload URL. A function gets the files and the data blocks [{ name, data, filename, chunkIndex? }]. Without a URL nothing is uploaded (files stay queued; the UI constructor throws No URL provided.); setting one later with setOption('url', ...) starts the queue. A <form action> can supply it in the UI. Example: '/upload'.
methodstring | (files, dataBlocks) => string'post'HTTP method, upper-cased. Example: 'put'.
withCredentialsbooleanfalseSend cookies on cross-origin requests.
timeoutnumber | null | (files) => number | nullnullRequest timeout in ms; null means none. A timeout fails with code TIMEOUT and is retried like a network error. Example: 30000.
headersRecord<string, string> | nullnullExtra headers on every request (uploads, manifest, status, finalize). Empty values are not sent. Example: { Authorization: 'Bearer ...' }.
defaultHeadersbooleantrueSend Accept: application/json, Cache-Control: no-cache and X-Requested-With: XMLHttpRequest.
paramsobject | (files, xhr, chunk) => object | nullnullExtra form fields, merged over the built-in ad* fields. A null value drops a built-in field, so you can rename it. chunk is { file, index, start, end, retries } or null. Example: params: (files, xhr, chunk) => ({ adUploadId: null, uploadId: files[0].upload.uuid }).
paramNamestring | (n) => string'file'Form field of the file (file[0], file[1], ... with uploadMultiple).
uploadMultiplebooleanfalseSend several files in one request, with indexed fields (file[0], adRelativePath[0], ...). The *multiple events fire once per request. Cannot be combined with chunking (the constructor throws).
binaryBodybooleanfalseSend the file (or chunk) as the raw body with Content-Type set to the file type, and no form fields. With chunking that means no ad* metadata reaches the server. Cannot be combined with uploadMultiple.
parallelUploadsnumber2Files uploading at once. A file holds its slot from processing to complete.
maxChunksInFlightnumber | nullnullOptional cap on upload requests in flight across the instance, shared round-robin between files. null means no cap (then at most parallelUploads times parallelChunkUploads). Example: 4.
autoQueuebooleantrueQueue accepted files when their batch closes. With false, files stay added until you call enqueueFile().
autoProcessQueuebooleantrueCall processQueue() after each batch and after each finished file. With false, every processQueue() call starts up to parallelUploads files once.
transportTransport | nullnullSends the requests. null means the built-in XMLHttpRequest transport. See Custom transport.
transformFile(file, done) => void | nullnullCalled when a file starts processing. Pass the blob to upload to done(blob). Chunk info is computed from that blob. When it returns a different blob, that file gets no chunk-level resume across reloads; a file passed through unchanged (done(file)) keeps resume. Throwing fails the file with TRANSFORM_FAILED.
renameFile((file) => string) | nullnullName sent to the server (file.upload.filename). Changes only the last segment of the sent path; relativePath and fingerprint keep the original name. Example: renameFile: (f) => f.name.toLowerCase().

Chunking ​

OptionTypeDefaultDescription
chunkingbooleanfalseSplit files larger than chunkSize into chunks.
forceChunkingbooleanfalseChunk files smaller than chunkSize too (a zero-byte file is one empty chunk).
chunkSizenumber2097152 (2 MiB)Chunk size in bytes. It is fixed per file when its first chunk is sent, so changing it later never moves the offsets of a file that already started. Example: 5 * 1024 * 1024.
parallelChunkUploadsboolean | numberfalseChunks of one file in flight: false means 1, true means parallelUploads, a number is that many (at least 1, Infinity for all).
retryChunksbooleantrueRetry failed chunk, manifest, chunk-status and finalize requests with backoff. Whole-file uploads are never retried automatically.
retryChunksLimitnumber3Retries per request, so at most 4 attempts.
chunksUploaded(file, done, instance) => void | nullnullReplaces the built-in finalize request. this is the options object. done() succeeds; done(new Error('...')), done('message') or throwing fails the file with FINALIZE_FAILED. Example: chunksUploaded(file, done) { fetch('/merge?id=' + file.upload.uuid).then(() => done(), done); }.
finalizeUrlstring | nullnullPOST target of the finalize request after the last chunk of a chunked file. Without it (and without chunksUploaded) the file succeeds after its last chunk.
chunkStatusUrlstring | nullnullGET ?uploadId= that returns the chunks the server already has. Asked only for files that are being resumed, never for fresh files. The server's answer wins; a 404 restarts the file with a new uploadId; complete: true lets a file finished in an earlier session be skipped. Without it, a 409 is not retried and the file fails with CHUNK_MISMATCH.

Validation ​

OptionTypeDefaultDescription
acceptedFilesstring | nullnullComma-separated list in the accept attribute syntax: .ext, type/*, type/subtype. Example: 'image/*,.pdf'. When a file has an empty MIME type (iOS HEIC photos), the type is guessed from its extension first.
maxFilesizenumber | null256Maximum size in MiB. null or 0 disables the check. Example: 2048.
maxFilesnumber | nullnullMaximum number of accepted files. Extra files are rejected and emit maxfilesexceeded. Example: 10.
accept(file, done) => voidcalls done()Your own check, called after the built-in ones. done() accepts, done(message) rejects (code REJECTED). It may be asynchronous; the batch waits for it. Example: accept(file, done) { file.size === 0 ? done('Empty file') : done(); }.
ignoreHiddenFilesbooleantrueSkip files whose name starts with . inside dropped or picked folders. Loose files and hidden folders are not skipped.
filesizeBasenumber1000Base used by filesize(). Example: 1024.

Folders ​

OptionTypeDefaultDescription
foldersbooleantrueAccept dropped folders (and, in the UI, show the folder picker where the browser supports it). When false, dropped folders are skipped.
preserveEmptyFoldersbooleantrueKeep empty folders in the tree and list them in the manifest.
sendManifestbooleanfalseSend the folder manifest (needs manifestUrl) right before a batch's first file. The files of the batch wait for it; if it fails after its retries they fail with stage: 'manifest'.
manifestUrlstring | nullnullPOST target of the manifest. Example: '/upload/manifest'.

Pause, resume and persistence ​

OptionTypeDefaultDescription
pauseMode'abort' | 'finishChunk''abort'What a pause does to requests in flight: abort them (the chunk is sent again in full later) or let them finish and count. Example: 'finishChunk'.
persistStatebooleantrueSave acknowledged chunks and finished files in IndexedDB so a reload can resume. false turns all of it off.
persistKeystring | nullnullScope of saved progress. null means url when it is a string, else 'default'. Include the user id in apps with logins, so one account never resumes another's upload. Example: 'user-42'.

Connectivity ​

OptionTypeDefaultDescription
autoPauseOnHiddenbooleantruePause on pagehide, and when a request fails while the page is hidden (how iOS suspension shows). A hidden desktop tab keeps uploading.
autoResumeOnReconnectbooleantrueResume when the browser comes back online, and probe by itself while the connection is lost. With false, nothing resumes or probes automatically: call reconnect() or resume().
stallTimeoutnumber | null30000Milliseconds without upload progress while a request body is sent (or four times that while waiting for the response) before the request is aborted and retried as STALLED. null turns the watchdog off. Custom transports must call onProgress. Example: 60000.
connectivityProbeUrlstring | nullnullHEAD target used to probe while the connection is lost. Any HTTP status counts as reachable (204 with Cache-Control: no-store is recommended; enable CORS if it is cross-origin). Without it, core probes with chunkStatusUrl or with the failed request itself. Example: '/upload/ping'.

UI ​

These options exist in @vedratech/anydrop-ui only.

OptionTypeDefaultDescription
clickableboolean | string | HTMLElement | (string | HTMLElement)[]truetrue (the element itself), false, a selector (every match), an element or an array. Clicking opens the file dialog. A selector that matches nothing throws.
previewsContainerstring | HTMLElement | null | falsenullWhere the toolbar, list and error panel go. null means inside the element; false means no previews.
previewTemplatestringthe built-in templateMarkup of one file's preview. The data-ad-name, data-ad-size, data-ad-thumbnail, data-ad-uploadprogress, data-ad-errormessage and data-ad-remove hooks are filled in. See Customising the UI.
hiddenInputContainerstring | HTMLElement'body'Where the hidden <input type=file> elements go.
addRemoveLinksbooleanfalseAdd a "Remove file" or "Cancel upload" link to each preview.
capturestring | nullnullPassed to the file input ('environment', 'user') to open the camera.
createImageThumbnailsbooleantrueCreate thumbnails for images.
maxThumbnailFilesizenumber10MiB. Larger images get no thumbnail.
thumbnailWidthnumber | null120Thumbnail width in px, capped at 512.
thumbnailHeightnumber | null120Thumbnail height in px, capped at 512. Both null means natural size, still capped at 512 px.
thumbnailMethod'crop' | 'contain''crop'How the image fits the thumbnail box.
resizeWidthnumber | nullnullScale images down to this width before upload.
resizeHeightnumber | nullnullScale images down to this height before upload.
resizeMethod'crop' | 'contain''contain'How the image fits the resize box.
resizeMimeTypestring | nullnullMIME type of the resized image; null keeps the type.
resizeQualitynumber0.8Encoder quality from 0 to 1.
disablePreviewsbooleanfalseNo preview elements, no list, no toolbar, no error panel. The zone and the pickers still work, and thumbnail events still fire.
forceFallbackbooleanfalseRender a plain form with a file input even when the browser supports everything.
fallback(() => void) | nullnullRuns when the browser lacks the needed APIs, or with forceFallback. null means the default form.
init(() => void) | nullnullCalled at the end of the constructor.
folderView'tree' | 'flat''tree'A collapsible tree, or a flat list of files with their full path. Can be changed with setOption.
rowHeightnumber | nullnullRow height in px of the virtualised list. null uses the height of the layout: 56 for list, 48 for compact. A number overrides it in every layout. Use a larger value for a taller previewTemplate. See Layouts.
toolbarbooleantrueShow the toolbar.
errorPanelbooleantrueShow the error panel when files failed.
pickerButtonsbooleantrueThe "Select files" and "Select folder" buttons. They appear only when the element itself is clickable.
enablePastebooleanfalseAdd files pasted into the element. Off by default.
theme'auto' | 'light' | 'dark''auto''auto' follows prefers-color-scheme. Combines with any themePreset.
layout'list' | 'compact''list'How files are laid out. compact is a denser row without a thumbnail. Can be changed with setOption. See Layouts.
errorRowHeightnumber64Height in px of a row of the error panel. Raise it when render.errorItem returns taller content.
renderAnyDropRenderHooks{}Hooks file, folder, toolbar, message and errorItem that decorate or replace the default content. See Render hooks.
rowActions{ file?, folder? }{ file: ['pause', 'resume', 'retry', 'cancel', 'remove'], folder: ['pause', 'resume', 'retry', 'cancel'] }The buttons of a row: built-in ids, overrides and custom actions. Merged per key. See Row actions and icons.
iconsAnyDropIcons | nullnullA record of SVG strings, or a function that returns one, to replace the built-in icons. See Row actions and icons.
localeAnyDropLocale | string | nullnullA language pack, or the code of one registered in AnyDrop.locales. null and 'en' mean the built-in English. Explicit dict* options win over it. See Languages and RTL.
dir'auto' | 'ltr' | 'rtl''auto'Text direction. 'auto' uses the direction of the locale, or inherits from the page when there is no locale.
themePresetstring | nullnullAdds the class ad-theme-<name> to the element and the panel, so a preset stylesheet applies. See Themes.

Texts ​

Every text is an option, so it can be translated. Texts are rendered as plain text, not HTML. A placeholder is replaced by the value of that name. See Customising the UI for an example.

Messages (core) ​

These come from @vedratech/anydrop-core and are used in error events and error entries.

OptionDefaultDescription
dictFileTooBig'File is too big (MiB). Max filesize: MiB.'A file is larger than maxFilesize.
dictInvalidFileType"You can't upload files of this type."A file does not match acceptedFiles.
dictMaxFilesExceeded'You cannot upload any more files.'A file is rejected because of maxFiles.
dictResponseError'Server responded with code.'The error message when the response has no body.
dictUploadCanceled'Upload canceled.'Shown by the UI for a canceled file; core emits no error on cancel.
dictFileUnreadable'The file could not be read (not downloaded, moved or deleted).'Code UNREADABLE, for example an iCloud placeholder.
dictInvalidPath'Invalid file path.'Code INVALID_PATH: a path with a .. segment.
dictFileSizeUnits{ tb: 'TB', gb: 'GB', mb: 'MB', kb: 'KB', b: 'b' }Unit labels of filesize(). A partial object is merged.

Interface texts (UI) ​

OptionDefaultDescription
dictDefaultMessageDrop files here to uploadText of the drop zone.
dictFallbackMessageYour browser does not support drag'n'drop file uploads.Shown when the browser lacks drag and drop.
dictFallbackTextPlease use the fallback form below to upload your files like in the olden days.Shown above the fallback form.
dictFallbackUploadUpload!Button of the fallback form.
dictCancelUploadCancel uploadaddRemoveLinks link while uploading.
dictCancelUploadConfirmationAre you sure you want to cancel this upload?Asked before canceling.
dictRemoveFileRemove fileaddRemoveLinks link when finished.
dictRemoveFileConfirmationnullQuestion asked before removing a finished file, through AnyDrop.confirm. null means no question.
dictThumbnailErrorFailed to load the image. The file may be corrupted.Screen-reader text and tooltip.
dictNoFolderSupportThis browser can only select files, not folders. Pick the files you need, or use a desktop browser to upload a whole folder.Notice where there is no folder picker (iOS).
dictSelectFilesSelect filesFile picker button.
dictSelectFolderSelect folderFolder picker button.
dictTapToUploadTap to uploadThe zone on touch devices.
dictPauseAllPause allToolbar button.
dictResumeAllResume allToolbar button.
dictRetryFailedRetry failedToolbar and error panel button.
dictClearClearToolbar button.
dictPausePauseRow button.
dictResumeResumeRow button.
dictRetryRetryRow button.
dictExpandExpand folderAccessible name of the folder toggle.
dictCollapseCollapse folderAccessible name of the folder toggle.
dictStatusAddedAddedRow status.
dictStatusQueuedQueuedRow status.
dictStatusUploadingUploadingRow status.
dictStatusPausedPausedRow status.
dictStatusSuccessDoneRow status.
dictStatusErrorFailedRow status.
dictStatusCanceledCanceledRow status.
dictSummary of uploaded, failedToolbar summary.
dictFolderCount/Count on a folder row.
dictErrorsTitle failedTitle of the error panel.
dictExportJsonExport JSONError panel button.
dictExportCsvExport CSVError panel button.
dictCopyErrorsCopy listError panel button.
dictCopiedCopied to the clipboard.Message after copying.
dictCopyFailedCould not copy the list.Message when copying failed.
dictDismissErrorsDismiss listError panel button.
dictRegionLabelFile uploadAccessible name of the zone.
dictListLabelFiles to uploadAccessible name of the list.
dictToolbarLabelUpload actionsAccessible name of the toolbar.
dictAnnounceAdded files added.Screen-reader message.
dictAnnounceCompleteUpload complete.Screen-reader message.
dictAnnounceErrors files failed.Screen-reader message.
dictAnnounceProgressUploading, percent.Screen-reader message.
dictAnnouncePausedUpload paused.Screen-reader message.
dictAnnounceResumedUpload resumed.Screen-reader message.
dictOfflineYou are offline. Uploads will continue when you are back online.Connection banner, browser offline.
dictReconnectingConnection lost. Retrying in sConnection banner, server unreachable.
dictRetryNowRetry nowBanner button; calls reconnect().
dictConnectionRestoredConnection restoredAnnounced when the banner hides.
dictWaitingForConnectionWaiting for connectionRow text instead of "Paused" while only the system holds the file.

Event handlers as options ​

Any event name can be given as an option: new AnyDropCore({ addedfile(file) { ... } }). The handler runs with this set to the instance. setOption('addedfile', fn) replaces it and setOption('addedfile', null) removes it. In the UI, handlers given as options run in addition to the built-in rendering; they do not replace it (set disablePreviews: true to render everything yourself).

Released under the MIT License.