Skip to content

Upload

Rules

Basic Example

js
const rule = {
    type: "upload",
    field: "pic",
    title: "Carousel",
    value: [
        'http://img1.touxiang.cn/uploads/20131030/30-075657_191.jpg',
        'http://img1.touxiang.cn/uploads/20131030/30-075657_191.jpg'
        ],
    props: {
        action: "/upload.php",
        limit: 2,
        onSuccess: function (file) {
            file.url = file.response.url;
        }
    },
}

Props Configuration Examples

Single Image Upload

js
const rule = {
    type: "upload",
    field: "avatar",
    title: "Avatar",
    value: [],
    props: {
        action: "/upload.php",
        listType: "picture-card",
        limit: 1,
        accept: "image/*",
        onSuccess: function (file) {
            file.url = file.response.url;
        }
    },
}

Multiple Image Upload

js
const rule = {
    type: "upload",
    field: "gallery",
    title: "Product Images",
    value: [],
    props: {
        action: "/upload.php",
        listType: "picture-card",
        multiple: true,
        accept: "image/*",
        limit: 9,
        onSuccess: function (file) {
            file.url = file.response.url;
        }
    },
}

File Upload

js
const rule = {
    type: "upload",
    field: "document",
    title: "Document Upload",
    value: [],
    props: {
        action: "/upload.php",
        accept: ".pdf,.doc,.docx",
        limit: 5,
        onSuccess: function (file) {
            file.url = file.response.url;
        }
    },
}

Drag Upload

js
const rule = {
    type: "upload",
    field: "images",
    title: "Drag Upload",
    value: [],
    props: {
        action: "/upload.php",
        listType: "picture-card",
        drag: true,
        multiple: true,
        accept: "image/*",
        onSuccess: function (file) {
            file.url = file.response.url;
        }
    },
}

Validation Before Upload

js
const rule = {
    type: "upload",
    field: "avatar",
    title: "Avatar",
    value: [],
    props: {
        action: "/upload.php",
        listType: "picture-card",
        limit: 1,
        accept: "image/*",
        beforeUpload: function (file) {
            // Validate file size (2MB)
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                alert('Image size cannot exceed 2MB');
                return false;
            }
            return true;
        },
        onSuccess: function (file) {
            file.url = file.response.url;
        }
    },
}

Events Examples

Listen to Upload Events

js
const rule = {
    type: "upload",
    field: "pic",
    title: "Image Upload",
    value: [],
    props: {
        action: "/upload.php",
        listType: "picture-card",
        accept: "image/*",
        onSuccess: function (file) {
            file.url = file.response.url;
        },
        onError: function (err, file) {
            console.log('Upload failed:', err, file);
        },
        onProgress: function (event, file) {
            console.log('Upload progress:', event.percent + '%');
        },
        onChange: function (info) {
            console.log('File state changed:', info);
        },
        onRemove: function (file) {
            console.log('Remove file:', file);
        },
    },
}

Complete configuration items: Ant-design-vue_Upload

value :Array | String

Note

After a file upload succeeds, you need to assign the URL from the interface response to file.url through the onSuccess callback. Otherwise, the form cannot get the component data.

Props

ParameterDescriptionTypeDefault
onSuccessUsed to get file link file.url = file.response.urlFunction(file,fileList)None
acceptAccept uploaded file types, see input accept Attributestring-
actionUpload addressstring|(file) => Promise-
beforeUploadHook before uploading file, parameter is uploaded file, if returns false then stop upload. Supports returning a Promise object, when Promise object rejects then stop upload, when resolves then start upload (if resolve passes File or Blob object then upload resolve passed object).(file, fileList) => boolean | Promise
customRequestBy overriding default upload behavior, can customize own upload implementationfunction-
dataParameters required for upload or method to return upload parametersobject|(file) => object-
directorySupport uploading folders (caniuse)booleanfalse
disabledWhether disabledboolean-
downloadIconCustom download iconv-slot:iconRender="{file: UploadFile}"-
fileListList of already uploaded files (controlled)object[]-
headersSet upload request headers, effective in IE10+object-
iconRenderCustom display iconv-slot:iconRender="{file: UploadFile, listType?: UploadListType}"-
isImageUrlCustom whether thumbnail uses tag for display(file: UploadFile) => boolean-
itemRenderCustom upload list itemv-slot:itemRender="{originNode: VNode, file: UploadFile, fileList: object[], actions: { download: function, preview: function, remove: function }"-
listTypeBuilt-in styles of upload list, supports three basic styles text, picture and picture-cardstringtext
maxCountLimit upload count. When 1, always replace current file with latest uploaded filenumber-
methodhttp method of upload requeststringpost
multipleWhether to support multiple file selection, ie10+ supports. After enabling, hold ctrl to select multiple files.booleanfalse
nameFile parameter name sent to backendstringfile
openFileDialogOnClickClick to open file dialogbooleantrue
previewFileCustom file preview logic(file: File | Blob) => Promise<dataURL: string>-
previewIconCustom preview iconv-slot:iconRender="{file: UploadFile}"-
progressCustom progress bar styleProgressProps (only supports type="line"){ strokeWidth: 2, showInfo: false }
removeIconCustom delete iconv-slot:iconRender="{file: UploadFile}"-
showUploadListWhether to display uploadList, can be set to an object, used to separately set showPreviewIcon, showRemoveIcon and showDownloadIconboolean | { showPreviewIcon?: boolean, showRemoveIcon?: boolean, showDownloadIcon?: boolean }true
supportServerRenderNeed to enable this for server-side renderingbooleanfalse
withCredentialsWhether to carry cookie in upload requestbooleanfalse

Events

Event NameDescriptionCallback Parameters
changeState when uploaded file changes, see changefunction
downloadCallback when clicking download file, if not specified, default jumps to file url corresponding tab.function(file): void
dropCallback function executed when file is dragged into upload area(event: DragEvent) => void
previewCallback when clicking file link or preview iconfunction(file)
rejectCallback when dragged file does not match accept typefunction(fileList)
removeCallback when clicking remove file, return false to not remove. Supports returning a Promise object, when Promise object resolve(false) or reject then not removefunction(file): boolean | Promise

UploadFile

Inherits from File, with additional properties for rendering.

ParameterDescriptionTypeDefault
crossOriginCORS property setting'anonymous' | 'use-credentials' | ''-
nameFile namestring-
percentUpload progressnumber-
statusUpload status, different statuses display different colorserror | success | done | uploading | removed-
thumbUrlThumbnail addressstring-
uidUnique identifier, automatically generated if not setstring-
urlDownload addressstring-

change

This function will be called during uploading, completion, and failure.

Callback when file status changes, returns:

jsx
{
  file: { /* ... */ },
  fileList: [ /* ... */ ],
  event: { /* ... */ },
}
  1. file Current file object being operated.
jsx
   {
      uid: 'uid',      // File unique identifier, recommended to set as negative number to prevent conflict with internally generated id
      name: 'xx.png',   // File name
      status: 'done', // Statuses: uploading done error removed
      response: '{"status": "success"}', // Server response content
      linkProps: '{"download": "image"}', // Additional HTML attributes for download link
      xhr: 'XMLHttpRequest{ ... }', // XMLHttpRequest Header
   }
  1. fileList Current file list.

  2. event Server response content during upload, contains upload progress and other information, supported by advanced browsers.

FormCreate is an open-source project released under the MIT License. Free for personal and commercial use.