Back to Ant Design

Upload

components/upload/index.en-US.md

6.3.713.9 KB
Original Source

When To Use

Uploading is the process of publishing information (web pages, text, pictures, video, etc.) to a remote server via a web page or upload tool.

  • When you need to upload one or more files.
  • When you need to show the process of uploading.
  • When you need to upload files by dragging and dropping.

Examples

<!-- prettier-ignore -->

<code src="./demo/basic.tsx">Upload by clicking</code> <code src="./demo/avatar.tsx">Avatar</code> <code src="./demo/defaultFileList.tsx">Default Files</code> <code src="./demo/picture-card.tsx">Pictures Wall</code> <code src="./demo/picture-circle.tsx">Pictures with picture-circle type</code> <code src="./demo/fileList.tsx">Complete control over file list</code> <code src="./demo/drag.tsx">Drag and Drop</code> <code src="./demo/paste.tsx" version="5.25.0">Paste</code> <code src="./demo/directory.tsx">Upload directory</code> <code src="./demo/upload-manually.tsx">Upload manually</code> <code src="./demo/upload-png-only.tsx">Upload png file only</code> <code src="./demo/picture-style.tsx">Pictures with list style</code> <code src="./demo/preview-file.tsx">Customize preview file</code> <code src="./demo/max-count.tsx">Max Count</code> <code src="./demo/transform-file.tsx">Transform file before request</code> <code src="./demo/upload-with-aliyun-oss.tsx">Aliyun OSS</code> <code src="./demo/file-type.tsx" debug>custom show icon</code> <code src="./demo/upload-custom-action-icon.tsx">Custom action icon and extra info</code> <code src="./demo/drag-sorting.tsx">Drag sorting of uploadList</code> <code src="./demo/crop-image.tsx">Crop image before uploading</code> <code src="./demo/customize-progress-bar.tsx">Customize Progress Bar</code> <code src="./demo/style-class.tsx" version="6.0.0">Custom semantic dom styling</code> <code src="./demo/component-token.tsx" debug>Component Token</code> <code src="./demo/debug-disabled.tsx" debug>Debug Disabled Styles</code>

API

Common props ref:Common props

PropertyDescriptionTypeDefaultVersion
acceptFile types that can be accepted. See input accept Attributestring | AcceptObject-
actionUploading URLstring | (file) => Promise<string>-
beforeUploadHook function which will be executed before uploading. Uploading will be stopped with false or a rejected Promise returned. When returned value is Upload.LIST_IGNORE, the list of files that have been uploaded will ignore it. Warning:this function is not supported in IE9(file: RcFile, fileList: RcFile[]) => boolean | Promise<File> | Upload.LIST_IGNORE-
customRequestOverride for the default xhr behavior allowing for additional customization and the ability to implement your own XMLHttpRequest( options: RequestOptions, info: { defaultRequest: (option: RequestOptions) => void; } ) => void-defaultRequest: 5.28.0
classNamesCustomize class for each semantic structure inside the component. Supports object or function.Record<SemanticDOM, string> | (info: { props })=> Record<SemanticDOM, string>-
dataUploading extra params or function which can return uploading extra paramsobject | (file) => object | Promise<object>-
defaultFileListDefault list of files that have been uploadedobject[]-
directorySupport upload whole directory (caniuse)booleanfalse
disabledDisable upload buttonbooleanfalseWhen customizing Upload children, please pass the disabled attribute to the child node at the same time to ensure the disabled rendering effect is consistent.
fileListList of files that have been uploaded (controlled). Here is a common issue #2423 when using itUploadFile[]-
headersSet request headers, valid above IE10object-
iconRenderCustom show icon(file: UploadFile, listType?: UploadListType) => ReactNode-
isImageUrlCustomize if render <img /> in thumbnail(file: UploadFile) => boolean(inside implementation)
itemRenderCustom item of uploadList(originNode: ReactElement, file: UploadFile, fileList: object[], actions: { download: function, preview: function, remove: function }) => React.ReactNode-4.16.0
listTypeBuilt-in stylesheets, support for four types: text, picture, picture-card or picture-circlestringtextpicture-circle(5.2.0+)
maxCountLimit the number of uploaded files. Will replace current one when maxCount is 1number-4.10.0
methodThe http method of upload requeststringpost
multipleWhether to support selected multiple files. IE10+ supported. You can select multiple files with CTRL holding down while multiple is set to be truebooleanfalse
nameThe name of uploading filestringfile
openFileDialogOnClickClick open file dialogbooleantrue
pastableSupport paste filebooleanfalse5.25.0
previewFileCustomize preview file logic(file: File | Blob) => Promise<dataURL: string>-
progressCustom progress barProgressProps (support type="line" only){ strokeWidth: 2, showInfo: false }4.3.0
showUploadListWhether to show default upload list, could be an object to specify extra, showPreviewIcon, showRemoveIcon, showDownloadIcon, removeIcon and downloadIcon individuallyboolean | { extra?: ReactNode | (file: UploadFile) => ReactNode, showPreviewIcon?: boolean | (file: UploadFile) => boolean, showDownloadIcon?: boolean | (file: UploadFile) => boolean, showRemoveIcon?: boolean | (file: UploadFile) => boolean, previewIcon?: ReactNode | (file: UploadFile) => ReactNode, removeIcon?: ReactNode | (file: UploadFile) => ReactNode, downloadIcon?: ReactNode | (file: UploadFile) => ReactNode }trueextra: 5.20.0, showPreviewIcon function: 5.21.0, showRemoveIcon function: 5.21.0, showDownloadIcon function: 5.21.0
stylesCustomize inline style for each semantic structure inside the component. Supports object or function.Record<SemanticDOM, CSSProperties> | (info: { props })=> Record<SemanticDOM, CSSProperties>-
withCredentialsThe ajax upload with cookie sentbooleanfalse
onChangeA callback function, can be executed when uploading state is changing. It will trigger by every uploading phase. see onChangefunction-
onDropA callback function executed when files are dragged and dropped into the upload area(event: React.DragEvent) => void-4.16.0
onDownloadClick the method to download the file, pass the method to perform the method logic, and do not pass the default jump to the new TABfunction(file): void(Jump to new TAB)
onPreviewA callback function, will be executed when the file link or preview icon is clickedfunction(file)-
onRemoveA callback function, will be executed when removing file button is clicked, remove event will be prevented when the return value is false or a Promise which resolve(false) or rejectfunction(file): boolean | Promise-

Interface

RcFile

Extends File.

PropertyDescriptionTypeDefaultVersion
uidunique id. Will auto-generate when not providedstring--
lastModifiedDateA Date object indicating the date and time at which the file was last modifieddate--

UploadFile

Extends File with additional props.

PropertyDescriptionTypeDefaultVersion
crossOriginCORS settings attributes'anonymous' | 'use-credentials' | ''-4.20.0
nameFile namestring--
percentUpload progress percentnumber--
statusUpload status. Show different style when configurederror | done | uploading | removed--
thumbUrlThumb image urlstring--
uidunique id. Will auto-generate when not providedstring--
urlDownload urlstring--

RequestOptions {#request-options}

PropertyDescriptionTypeDefaultVersion
actionUploading URLstring--
dataUploading extra params or function which can return uploading extra paramsRecord<string, unknown>-4.20.0
filenamefile namestring--
fileFile object containing upload informationUploadFile--
withCredentialsThe ajax upload with cookie sentboolean--
headersSet request headers, valid above IE10Record<string, string>--
methodThe http method of upload requeststring--
onProgressProgress event callback(event: object, file: UploadFile) => void--
onErrorError callback when upload fails(event: object, body?: object) => void--
onSuccessSuccess callback when upload completes(body: object, fileOrXhr?: UploadFile | XMLHttpRequest) => void--

onChange

💡 The function will be called when uploading is in progress, completed, or failed.

When uploading state change, it returns:

jsx
{
  file: { /* ... */ },
  fileList: [ /* ... */ ],
  event: { /* ... */ },
}
  1. file File object for the current operation.

    jsx
    {
       uid: 'uid',      // unique identifier, negative is recommended, to prevent interference with internally generated id
       name: 'xx.png',   // file name
       status: 'done' | 'uploading' | 'error' | 'removed', // Intercepted file by beforeUpload doesn't have a status field.
       response: '{"status": "success"}', // response from server
       linkProps: '{"download": "image"}', // additional HTML props of file link
       xhr: 'XMLHttpRequest{ ... }', // XMLHttpRequest Header
    }
    
  2. fileList current list of files

  3. event response from the server, including uploading progress, supported by advanced browsers.

AcceptObject

typescript
{
  format: string;
  filter?: 'native' | ((file: RcFile) => boolean);
}

Configuration object for file type acceptance rules.

PropertyDescriptionTypeDefaultVersion
formatAccepted file types, same as native input accept attribute. Supports MIME types, file extensions, etc. See input accept Attributestring-
filterFile filtering rule. When set to 'native', uses browser native filtering behavior; when set to a function, allows custom filtering logic. Function returns true to accept the file, false to reject'native' | (file: RcFile) => boolean-

Semantic DOM

<code src="./demo/_semantic.tsx" simplify="true"></code>

Design Token

<ComponentTokenTable component="Upload"></ComponentTokenTable>

FAQ

How do I implement upload server side? {#faq-server-implement}

  • You can consult jQuery-File-Upload about how to implement server side upload interface.
  • There is a mock example of express in rc-upload.

Please set property url of each item in fileList to control the content of the link.

How to use customRequest? {#faq-custom-request}

See https://github.com/react-component/upload#customrequest.

Why will the fileList that's in control not trigger onChange status update when the file is not in the list? {#faq-filelist-controlled-status}

onChange will only trigger when the file is in the list, it will ignore any events removed from the list. Please note that there does exist a bug which makes an event still trigger even when the file is not in the list before 4.13.0.

Why does onChange sometimes return File object and other times return { originFileObj: File }? {#faq-on-change-return-type}

For compatible case, we return File object when beforeUpload return false. It will merge to { originFileObj: File } in the next major version. Current version is compatible to get origin file by info.file.originFileObj. You can change this before a major release.

Why sometimes Chrome can not upload? {#faq-chrome-file-picker}

Chrome update will also break native upload. Please restart Chrome to finish the upload job.

Ref:

Can still select files when uploading a folder in Safari? {#faq-safari-folder-upload}

Inside the upload component, we use the directory and webkitdirectory properties to control the input to implement folder selection, but it seems that in Safari's implementation, it doesn't prevent users from selecting files. You can solve this issue through accept configuration, for example:

tsx
accept = {
  // Do not allow selecting any files
  format: `.${'n'.repeat(100)}`,
  // Accept all files within the folder after folder selection
  filter: () => true,
};