upup: Drag & Drop File Upload Library for JavaScript

Category: Form , Javascript | November 23, 2026
AuthorDevinoSolutions
Last UpdateNovember 23, 2026
LicenseMIT
Views0 views
upup: Drag & Drop File Upload Library for JavaScript

upup is an open-source JavaScript file uploader with drag-and-drop selection, file previews, and direct transfers to S3-compatible storage.

Uploads use presigned URLs from your backend. The optional @useupup/server package handles signing, multipart transfers, and cloud-drive OAuth.

Features

  • File imports from cloud drives, URLs, camera, microphone, and screen capture.
  • Limits for file count, accepted types, file size, and total upload size.
  • Retry controls and resumable transfers through S3 multipart or tus.
  • Optional image compression, HEIC conversion, thumbnails, and checksums.
  • Network-aware pause/resume and optional IndexedDB crash recovery.
  • Dark mode, localization, theme tokens, and component styling slots.
  • Programmatic file management, state subscriptions, and upload events.
  • Works with Vanilla JS, React, Vue, Svelte, Angular, and Preact.

How To Use It

Install and mount the Vanilla JS uploader

npm i @useupup/vanilla

Add a container to the page:

<div id="uploader"></div>

Mount createUploader(target, options) on a CSS selector or an HTMLElement. The example below accepts JPEG, PNG, and PDF files up to 10 MB each. Uploads use a same-origin /api/upload-token route, implemented in the next step.

import { createUploader } from '@useupup/vanilla';
import '@useupup/vanilla/styles';
const uploader = createUploader('#uploader', {
  provider: 'aws',
  uploadEndpoint: '/api/upload-token',
  allowedFileTypes: ['image/jpeg', 'image/png', 'application/pdf'],
  maxFileSize: { size: 10, unit: 'MB' },
  onUploadComplete(files) {
    console.log('Uploaded files:', files);
  },
  onError(message) {
    console.error(message);
  }
});

Create the S3 presign endpoint

The backend issues a short-lived upload URL for each file. This Express example uses the AWS SDK, generates its own object keys, and checks file types and sizes before signing.

It assumes your application already has login-session middleware and exposes the authenticated ID as req.session.userId. Register that middleware before the route.

Install the server dependencies in your Node.js backend:

npm i express @aws-sdk/client-s3 @aws-sdk/s3-request-presigner

Add this route to your existing Express app (ES modules). Here, app is your Express instance and express is its imported module:

import { randomUUID } from 'node:crypto';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
// Your app and authenticated-session middleware are already configured.
app.use(express.json({ limit: '16kb' }));
const s3 = new S3Client({
  region: process.env.S3_REGION,
  requestChecksumCalculation: 'WHEN_REQUIRED'
});
const types = new Map([
  ['image/jpeg', 'jpg'],
  ['image/png', 'png'],
  ['application/pdf', 'pdf']
]);
const maxBytes = 10 * 1024 * 1024;
app.post('/api/upload-token', async (req, res) => {
  const userId = req.session?.userId;
  if (!userId) return res.status(401).json({ error: 'Sign in required' });
  const { type, size } = req.body ?? {};
  const extension = types.get(type);
  if (!extension) return res.status(415).json({ error: 'File type not accepted' });
  if (!Number.isInteger(size) || size < 1 || size > maxBytes) {
    return res.status(413).json({ error: 'File must be 10 MB or smaller' });
  }
  const key = `uploads/${encodeURIComponent(String(userId))}/${randomUUID()}.${extension}`;
  try {
    const uploadUrl = await getSignedUrl(
      s3,
      new PutObjectCommand({
        Bucket: process.env.S3_BUCKET,
        Key: key,
        ContentType: type,
        ContentLength: size
      }),
      {
        expiresIn: 300,
        signableHeaders: new Set(['content-type', 'content-length'])
      }
    );
    res.json({
      key,
      uploadUrl,
      uploadHeaders: { 'Content-Type': type },
      expiresIn: 300
    });
  } catch (error) {
    console.error('S3 signing failed:', error);
    res.status(500).json({ error: 'Unable to prepare upload' });
  }
});

Provide S3_BUCKET and S3_REGION as server environment variables. The AWS SDK reads server credentials from an IAM role or the standard AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables. Grant that identity s3:PutObject for the bucket’s uploads/* prefix. For example, attach this IAM policy with YOUR_BUCKET replaced by the actual bucket name:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": "s3:PutObject",
    "Resource": "arn:aws:s3:::YOUR_BUCKET/uploads/*"
  }]
}

Leave bucket public access blocked. This route signs the declared Content-Type and file length, and upup uses the returned uploadHeaders for the direct browser-to-S3 PUT.

In the S3 bucket’s Permissions > Cross-origin resource sharing (CORS) section, use the following JSON array. Replace the example origins with the exact origins serving your uploader:

[
  {
    "AllowedOrigins": ["http://localhost:3000", "https://your-site.example"],
    "AllowedMethods": ["PUT"],
    "AllowedHeaders": ["content-type"],
    "ExposeHeaders": ["ETag"]
  }
]

Load the browser module from a CDN

For browser-only pages, load the package stylesheet and ES module from a CDN.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@useupup/vanilla/dist/tailwind-prefixed.css">
<div id="uploader"></div>
<script type="module">
  import { createUploader } from 'https://cdn.jsdelivr.net/npm/@useupup/vanilla/+esm';
  createUploader('#uploader', {
    provider: 'aws',
    uploadEndpoint: '/api/upload-token',
    allowedFileTypes: ['image/jpeg', 'image/png', 'application/pdf'],
    maxFileSize: { size: 10, unit: 'MB' }
  });
</script>

Collect files before sending them

For a file picker that does not upload immediately, restrict sources to local files and handle onFileAdded.

const picker = createUploader('#uploader', {
  sources: ['local'],
  maxFiles: 5,
  allowedFileTypes: 'images,documents',
  onFileAdded(files) {
    console.log('Selected:', files.map(file => file.name));
  }
});

Set file restrictions and upload behavior

Set the accepted file types and size limits in the uploader. Enforce the same restrictions and user permissions in your backend’s signing route.

createUploader('#uploader', {
  provider: 'aws',
  uploadEndpoint: '/api/upload-token',
  maxFiles: 5,
  allowedFileTypes: ['image/jpeg', 'image/png', 'application/pdf'],
  maxFileSize: { size: 10, unit: 'MB' },
  maxTotalFileSize: { size: 30, unit: 'MB' },
  autoUpload: false,
  onBeforeFileAdded(file) {
    return file.size > 0;
  }
});

Add capture tools and cloud drives

The sources array controls which file sources appear and in what order.

createUploader('#uploader', {
  provider: 'aws',
  uploadEndpoint: '/api/upload-token',
  sources: ['local', 'camera', 'screen', 'url', 'googleDrive', 'oneDrive'],
  cloudDrives: {
    googleDrive: {
      clientId: 'YOUR_GOOGLE_CLIENT_ID',
      apiKey: 'YOUR_GOOGLE_API_KEY',
      appId: 'YOUR_GOOGLE_APP_ID'
    },
    oneDrive: { clientId: 'YOUR_ONEDRIVE_CLIENT_ID' }
  }
});

Use the server package

For multipart uploads and server-managed cloud-drive access, mount @useupup/server on your backend.

This example extends the Express application used above and replaces the custom presign endpoint for requests made in server mode.

npm i @useupup/server

Generate a high-entropy secret once with openssl rand -hex 32 and store it as UPUP_UPLOAD_TOKEN_SECRET on the server. It must contain at least 16 characters and have the same value on every server instance.

The following middleware reads the authenticated session, rejects unknown users, and passes a trusted user ID to upup. It overwrites any incoming header of that name before the upup handler reads it.

import { createUpupMiddleware } from '@useupup/server/express';
app.use('/api/upup', (req, res, next) => {
  const userId = req.session?.userId;
  if (!userId) return res.status(401).json({ error: 'Sign in required' });
  req.headers['x-upup-authenticated-user'] = String(userId);
  next();
}, createUpupMiddleware({
  storage: {
    type: 'aws',
    bucket: process.env.S3_BUCKET,
    region: process.env.S3_REGION
  },
  uploadTokenSecret: process.env.UPUP_UPLOAD_TOKEN_SECRET,
  getUserId: async request => request.headers.get('x-upup-authenticated-user'),
  maxFileSize: 10 * 1024 * 1024,
  allowedTypes: ['image/jpeg', 'image/png', 'application/pdf']
}));

Mount express.json() before this middleware. For multipart uploads, also grant the signing identity s3:AbortMultipartUpload and s3:ListMultipartUploadParts on the relevant objects.

The handler responds under /api/upup/presign and /api/upup/multipart/*. Use the following client setup to switch from your own signing route to the built-in handler:

createUploader('#uploader', {
  provider: 'aws',
  mode: 'server',
  serverUrl: '/api/upup',
  sources: ['local'],
  allowedFileTypes: ['image/jpeg', 'image/png', 'application/pdf'],
  maxFileSize: { size: 10, unit: 'MB' }
});

Local-file bytes still travel directly from the browser to S3. To enable server-managed Google Drive, OneDrive, Dropbox, or Box imports, add the provider’s OAuth credentials to providers, register its callback URL under /api/upup/auth/<provider>/cb, and supply a persistent per-user tokenStore for refresh tokens.

Configure resumable uploads

The /api/upup handler above signs multipart transfers. crashRecovery restores the upload state after a reload, and multipart persistence can continue from completed parts.

Set an S3 AbortIncompleteMultipartUpload lifecycle rule to delete abandoned parts after several days. If using tus, provide an external tus server URL as resumable.endpoint.

createUploader('#uploader', {
  provider: 'aws',
  mode: 'server',
  serverUrl: '/api/upup',
  resumable: {
    protocol: 'multipart',
    thresholdBytes: 50 * 1024 * 1024,
    chunkSizeBytes: 8 * 1024 * 1024,
    persist: true
  },
  crashRecovery: true
});

Customize the theme

Set theme.mode to light, dark, or system. Adjust colors and spacing with tokens, or attach CSS classes through theme.slots.

createUploader('#uploader', {
  provider: 'aws',
  uploadEndpoint: '/api/upload-token',
  theme: {
    mode: 'dark',
    tokens: {
      color: { primary: '#16a34a', primaryHover: '#15803d' },
      radius: { md: '12px' }
    },
    slots: {
      sourceSelector: { sourceButton: 'my-source-button' }
    }
  }
});

Use the custom element

The Vanilla JS package exports an <upup-uploader> custom element. Import its registration module and assign config before appending the element. The property accepts the same CreateUploaderOptions as createUploader().

import '@useupup/vanilla/element';
import '@useupup/vanilla/styles';
const element = document.createElement('upup-uploader');
element.config = {
  provider: 'aws',
  uploadEndpoint: '/api/upload-token'
};
document.querySelector('#uploader').append(element);
element.addEventListener('upup:upload-complete', event => {
  console.log(event.detail);
});

Vanilla JS Configuration Reference

Upload target and reliability

OptionDescription
providerStorage provider ID, such as 'aws'; optional for local file collection.
mode'client' or 'server'. Defaults to client unless only serverUrl is supplied.
uploadEndpointApplication route returning presigned upload credentials in client mode.
serverUrlBase URL of an @useupup/server handler.
autoUploadUpload immediately after file selection. Default false.
maxConcurrentUploadsConcurrent transfer limit. Default 3.
maxRetriesRetry allowance for failed uploads. Default 3.
networkAwarePause for lost connectivity and resume on reconnection. Default true.
resumableMultipart transfer settings for @useupup/server or tus settings for an external tus server.
crashRecoverySave upload state to IndexedDB; accepts true or { storage? }. Default false.
metadataApplication metadata attached to upload signing requests.
corsCORS configuration object with allowedOrigins, optional allowedMethods, allowedHeaders, maxAgeSeconds, and dangerouslyAutoConfigure.

File selection and validation

OptionDescription
maxFilesMaximum number of selected files. Default 10; mini mode forces 1.
allowedFileTypesMIME filters, extensions, or preset names supplied as a string or string array. Default '*'.
maxFileSizePer-file size limit as { size, unit }. Default { size: 1, unit: 'GB' }.
minFileSizeOptional per-file minimum using { size, unit }.
maxTotalFileSizeOptional combined-size ceiling using { size, unit }.
contentDeduplicationReject files with duplicate content when enabled.
onBeforeFileAddedSync or async file filter; return false, a replacement File, or an acceptance value.
folderUpload{ allowDrop?, showSelectFolderButton? }; both settings default to false.
enablePasteAccept file content from the clipboard. Default false.

File size units are B, KB, MB, GB, TB, PB, EB, ZB, and YB. Useful type presets include images, documents, video, audio, spreadsheets, archives, and code.

Sources and appearance

OptionDescription
sourcesOrdered source IDs: local, url, camera, microphone, screen, googleDrive, oneDrive, dropbox, box. Defaults to the five non-cloud sources.
cloudDrivesGoogle Drive { clientId, apiKey, appId, sharedDrives? }; OneDrive, Dropbox, and Box { clientId, redirectUri? }.
theme{ mode?, tokens?, slots? }; mode accepts light, dark, or system.
darkVanilla-specific boolean theme shortcut; theme takes precedence.
i18n{ bundle?, locale?, fallbackLocale?, overrides? } for language bundles and translated labels.
classNameExtra class on the uploader root.
miniCompact uploader with one-file limit. Default false.
allowPreviewEnable expanded previews. Default true.
showBrandingDisplay the branding footer. Default true.
disableDragDropDisable drag-and-drop input. Default false.
animationsEnable decorative animation. Default true.
quietCompletionShow a short completion indicator in place of Done controls. Default false.
isProcessingHost-controlled busy state that blocks new file input. Default false.
imageEditorAccepted option, but crop/rotate/annotation UI is available only in React and Preact.

File processing

OptionDescription
imageCompressionEnable compression or pass processing options.
thumbnailGeneratorEnable image or video thumbnails or pass processing options.
checksumVerificationOptional SHA-256 checksum processing.
heicConversionConvert HEIC/HEIF images to JPEG when enabled.
stripExifDataRemove image EXIF metadata when enabled.
webWorkerUse background workers for eligible processing tasks; false forces the main thread.

resumable supports two protocols:

  • Multipart: { protocol: 'multipart', thresholdBytes?, chunkSizeBytes?, persist?, retryDelays?, partTimeoutMs?, maxConcurrentParts?, autoResume? }.
  • tus: { protocol: 'tus', endpoint, chunkSizeBytes?, chunkSize?, retryDelays?, storeFingerprintForResuming?, removeFingerprintOnSuccess?, headers?, metadata?, parallelUploads? }.

Theme tokens and CSS hooks

theme.tokens accepts the following groups. A token becomes a CSS custom property in the form --upup-<group>-<key>, with camelCase keys converted to kebab-case.

Token groupAvailable keys
colorsurface, surfaceAlt, primary, primaryHover, text, textMuted, border, borderActive, danger, success, dragBg, overlay.
radiussm, md, lg, full.
shadowsm, md, lg.
spacingxs, sm, md, lg.

Theme slot class overrides

theme.slots accepts the following class-name overrides.

GroupAvailable class-name keys
uploaderroot, container.
dropZoneroot.
sourceSelectorroot, sourceList, sourceButton, sourceButtonIcon, sourceButtonText, browseText, dragText.
sourceViewroot, header, cancelButton.
fileListroot, header, cancelButton, addMoreButton, fileCount, body, footer, uploadButton, doneButton.
filePreviewroot, thumbnail, icon, info, name, size, previewButton, deleteButton.
progressBarroot, track, fill, text.
notifierroot, message.
urlUploaderinput, fetchButton.
cameraUploaderpreviewContainer, deleteButton, captureButton, rotateButton, mirrorButton, addButton, modeToggle, videoRecordButton, videoStopButton, videoPreview, videoAddButton, videoDeleteButton.
audioUploaderroot, playbackContainer, deleteButton, addButton.
screenCaptureUploaderroot, preview, addButton, deleteButton.
driveBrowserroot, header, searchContainer, searchInput, body, footer, itemDefault, itemSelected, itemInner, itemInnerText, addFilesButton, cancelFilesButton, logoutButton, loading.
driveAuthFallbackroot.
filePreviewPortalroot.

The imageEditor group (root, modal) belongs to the React and Preact editor, which is unavailable in Vanilla JS.

For CSS overrides, target data-upup-slot attributes such as uploader-panel, source-selector, file-list, and progress-bar.

[data-upup-slot='uploader-panel'] {
  border-radius: var(--upup-radius-md);
}
[data-upup-slot='progress-bar'] {
  --upup-color-primary: #16a34a;
}

Instance Methods and Properties

Method or propertyDescription
getState()Return the current snapshot with files, status, progress, error, activeSource, and viewMode.
subscribe(callback)Immediately send a snapshot, listen for updates, and return an unsubscribe function.
addFiles(files)Add native File objects to the current selection; returns a promise.
setFiles(files)Replace the selected files; returns a promise.
removeFile(id)Remove a file using its uploader ID.
removeAll()Clear the selected files.
reorderFiles(ids)Set file display order using an array of IDs.
upload()Start transfers for selected files; returns a promise.
pause()Pause the current upload.
resume()Resume a paused upload.
cancel()Cancel the active upload.
retry(fileId?)Retry one file or unfinished files; returns a promise.
on(event, handler)Register an upload/core event and return an unsubscribe function.
destroy()Detach listeners, stop rendering, and clear the mounted view.
coreAccess the underlying UpupCore instance.
extAccess registered extension method groups.
elAccess the mounted HTML element.

For status-driven UI, subscribe to snapshots and clean up the subscription when the host view unmounts:

const unsubscribe = uploader.subscribe(state => {
  console.log(state.status, state.progress.percentage);
});
const stopErrors = uploader.on('upload-error', ({ error, file }) => {
  console.error(file?.name ?? 'Upload', error);
});
// On teardown:
unsubscribe();
stopErrors();
uploader.destroy();

Callbacks and Events

Vanilla JS callbacks

CallbackDescription
onFileAdded(files)Accepted files enter the list.
onFileRemoved(file)A selected file is removed.
onUploadProgress(progress)Receive { fileId, loaded, total } during transfer.
onUploadComplete(files)The upload batch reaches its completion event.
onDoneClicked()The Done action is clicked.
onIntegrationClick(sourceId)A file-source tile is selected.
onFilesDragOver(files)Files are dragged over the drop area.
onFilesDragLeave(files)A drag leaves the drop area.
onFilesDrop(files)Files are dropped.
onWarn(message)Report a warning.
onError(message)Report an error message.

Core events

EventWhen it fires
state-changeA state field changes.
upload-start, file-upload-startA batch or one file starts transferring.
upload-progress, upload-success, upload-errorTransfer progress, per-file success, or failure.
upload-all-completeAll files in the batch have a storage key.
upload-pause, upload-resume, upload-cancel, retryTransfer control is used.
destroyedThe core is destroyed.
files-added, file-removed, files-clearedFiles enter or leave the selection.
file-rejected, restriction-failedA file is filtered out or fails a restriction.
file-replaced, files-set, files-reorderedExisting file contents, selection, or ordering changes.
plugin-registered, options-updatedCore plugin registration or option updates.
snapshot-restored, crash-recovery-restoredA saved file state is recovered.
done, state-reset, auto-uploadA completion action, reset, or automatic upload occurs.
connection-online, connection-offlineBrowser connectivity changes.
drag-over, drag-leave, drop, folder-drop-blocked, pasteDrag, folder, and clipboard activity.
pipeline-start, pipeline-step, pipeline-complete, pipeline-errorFile-processing pipeline stages and diagnostics.
source-click, source-view-cancel, browse-files, folder-selectPicker and source navigation.
url-submit, url-fetch, url-fetch-cancelURL import activity.
camera-capture, camera-confirmCamera input activity.
file-preview-open, file-preview-closeFile preview panel activity.

Alternatives and Related Resources

You Might Be Interested In:


Leave a Reply