本文へ移動
日本語

仕組み

The component sends no requests: you supply upload(), so it works with any backend. Files are checked against accept, maxSize and maxCount first, and rejections explain themselves in a fixed message line so nothing below jumps. Each row has a page badge whose tag is coloured by file family (PDF, image, document, sheet, archive, media), the name with a percentage, a 6px pill bar, and the bytes done with pill actions: Cancel while uploading, Change and Remove when done, Retry and Remove after a failure. A row keeps its height in every state, so the list never shifts while files finish.

向いている場面

  • Forms that take files: receipts, ID photos, supporting documents, attachments.
  • When people need to see each file's progress and retry a failed one: use list.
  • For images with visible thumbnails, such as a photo wall: use picture.
  • With format, size or count limits: set accept, maxSize and maxCount, and state them in hint up front.

向かない場面

  • Changing a single avatar: a clickable avatar with a file picker is enough, with no list or progress.
  • Multi-gigabyte files that need resumable uploads: this component sends one request per file.
  • Only reading a local file's contents, such as a CSV import: use a button with <input type="file">.
  • Cropping, sorting or captioning after upload: upload first, then edit in a separate screen.

使い方

import { useState } from 'react'
import { Upload } from './Upload.jsx'

// How to upload is up to you: XMLHttpRequest is used here because it reports progress
const upload = (file, { onProgress, signal }) =>
  new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open('POST', '/api/files')
    xhr.upload.onprogress = (e) => onProgress((e.loaded / e.total) * 100)
    xhr.onload = () => (xhr.status < 300 ? resolve(JSON.parse(xhr.responseText)) : reject(new Error('Server rejected the file')))
    xhr.onerror = () => reject(new Error('Connection lost'))
    signal.addEventListener('abort', () => xhr.abort())
    const body = new FormData()
    body.append('file', file)
    xhr.send(body)
  })

export function Attachments() {
  const [files, setFiles] = useState([])
  return (
    <Upload
      fileList={files}
      onChange={setFiles}
      upload={upload}
      accept="image/*"
      maxSize={5 * 1024 * 1024}
      maxCount={3}
      hint="JPG / PNG, up to 5 MB each, at most 3"
    />
  )
}

// Thumbnail grid, managed by the component itself
// <Upload variant="picture" upload={upload} accept="image/*" maxCount={6} />

プロパティ

プロパティ型既定値説明
variant'list' | 'picture''list'list: upload zone plus file list; picture: thumbnail grid with a “+” cell.
upload(file, { onProgress, signal }) => Promise—Required. Uploads one file: resolve for success (a returned { url } is stored on the file), reject for failure (the Error message is the reason). signal aborts on removal, clearing and unmount.
fileListUploadFile[]—Controlled file list. When omitted, the component manages it.
defaultFileListUploadFile[]—Initial list when uncontrolled, such as files already uploaded: { uid, name, size, status: 'done', url }.
onChange(fileList) => void—Called on every change to the list: added, progress, success, failure, removal.
UploadFile{ uid, name, size, type?, status, percent?, error?, url?, thumbUrl?, file?, response? }—status is 'uploading', 'done' or 'error'; percent is 0–100; file is the original File, and without it there is no retry button.
acceptstring—Allowed formats, same syntax as <input accept>: '.jpg,.png', 'image/*'. Other files stay out of the list with an explanation.
maxSizenumber—Maximum size of one file, in bytes.
maxCountnumber—Maximum number of files. At the limit the zone is disabled (the “+” cell disappears in picture) until one is removed.
multiplebooleantrueWhether several files can be chosen at once. Defaults to false when maxCount is 1.
disabledbooleanfalseCannot choose, drop, change, remove or retry.
changeablebooleantrueShows a Change pill on finished files in list: it opens the picker for one file that takes that row's place (the count limit allows for the swap).
titleReactNode'Click or drag files here'Main text in the zone; wrap a word such as “browse” in <strong> to show it in the accent colour. In picture it is the small text under the “+”, “Upload image” by default.
hintReactNode—The line under the zone: formats, size, count. When a file is rejected, it shows the reason instead.
labelsobject—Replaces built-in text (title, pictureTitle, full, uploading, uploaded, completed, sizeProgress, changeText, removeText, cancelText, retryText, change, uploadedLive, failed, failedShort, failedRetry, tryAgain, failedLive, rejectAccept, rejectSize, rejectCount, rejectMore, progress, retry, retryFailed, cancel, remove, pictureList, fileList). The *Text entries are the visible pill words; change, retry, cancel and remove are their accessible names and should contain those words. Shallow-merged over the English defaults.
onReject(rejections: { file, reason, message }[]) => void—Called when files are rejected; reason is 'accept', 'size' or 'count'. The message already shows in place; use this for extra handling.
ref{ open(), add(files) }—open() opens the file picker; add() hands over files from elsewhere (paste, another drop zone) with the same checks.
...restHTMLAttributes<HTMLDivElement>—Other attributes, such as className, go to the root element. Set --ds-upload-bar on it to change the fill colour while uploading (accent by default).

アクセシビリティ

  • The zone is a real <button>: reachable by Tab, opens the picker with Enter or Space, and has a focus ring; the hint is linked with aria-describedby.
  • While a file uploads its bar is a progressbar named “<file> upload progress” (the counting percentage is hidden from screen readers); completion and failure are announced as “<file> uploaded” or “failed to upload: reason”.
  • Rejection reasons use role="alert" and appear under the zone, with no dialog.
  • Cancel, Change, Retry and Remove are buttons with visible words and names that contain them (“Remove passport-scan.jpg”). After removal, focus moves to the neighbouring file's button, or back to the zone; after Change, to the new file's button.
  • Completed and failed are not only colour: each has an icon and a word, and a failure states its reason. On touch screens, pill tap areas grow to 44px.

モーション

New rows rise 6px and fade in over 320ms ease-out, 60ms apart; a removed row fades and shrinks to 0.97 in 200ms (no height animation). The bar fill slides with a 320ms ease-out transform and the percentage and byte count count in step with it; on completion the bar turns green and the Completed mark and pills pop in with a spring. The drop zone icon lifts on hover and on drag-over. With no progress yet, a short segment slides back and forth every 1.2s. Reduced motion: values jump, nothing pops.

プロジェクトに追加

プロンプトを Codex または Claude Code に貼り付けます。エージェントが公開ソースを読み、書き込む内容を示したうえで、既存のコンポーネントの隣に追加します。

Upload.jsxupload.csstokens.cssREADME.md

2 つのファイルを一緒に導入します。スタイルは tokens.css の変数を読み、予備の値も持つため、単体でも表示できます。

フォーム入力
「空き時間グリッド」は Pro に含まれます。解除するとプレビューが表示されます。
「図形のブール演算」は Pro に含まれます。解除するとプレビューが表示されます。
「カスケード選択」は Pro に含まれます。解除するとプレビューが表示されます。