Skip to content

Upload Component ​

The upload component provides file upload functionality, supporting various file types such as images, documents, videos, and audio. Offers rich configuration options including multi-file upload, file preview, upload progress monitoring, and more.

Basic Usage ​

Set Upload Success Callback ​

In the upload component's onSuccess callback, assign the URL after successful upload to file.url, otherwise the form won't be able to get file data:

js
function onSuccess($inject) {
   const res = $inject.args[0];
   const file = $inject.args[1];
   // Assign the URL after upload to file.url
    file.url = res.data.url;
}

This ensures the form can correctly get uploaded file information when submitting.

Set Request Headers ​

When uploading files, the form's beforeFetch event is triggered. Modify request headers in this event callback, for example, adding an authentication token:

js
function beforeFetch(config, data) {
    // Get global token from external data
    const token = data.api.getData('globalToken');
    if (!config.headers) {
        config.headers = {};
    }
    config.headers.token = token;
}

Save More Data ​

If you expect the upload component's value type to be object[], assign the upload result data to file.value:

js
function onSuccess($inject) {
   const res = $inject.args[0];
   const file = $inject.args[1];
    file.url = res.data.url;
    file.name = res.data.name;
    file.value = res.data;  // Save complete returned data
}

Global Configuration ​

In actual projects, it's usually necessary to set unified upload address, success callback, and request headers for all upload components. FormCreate provides three ways to set global configuration, in execution order:

  1. formCreate.parser (Global replacement configuration) - Directly modifies the rule itself, executes earliest
  2. option.global (Normal configuration) - Only takes effect when the rule doesn't have the corresponding property
  3. option.global.deep (Deep merge configuration) - Forcibly overrides properties with the same name in rules

Execution Order

Execution Order: Parser → option.global (Normal configuration) → option.global.deep (Deep merge)

For detailed instructions, see: Set Component Default Configuration

Register a parser through formCreate.parser to directly modify the rule itself. Suitable for scenarios requiring forced unification of all upload component configurations.

Register Parser in main.js:

js
// main.js
import formCreate from '@form-create/element-ui';

formCreate.parser({
  name: 'upload',
  merge: true,
  init({rule}) {
    // Directly modify the rule itself
    rule.props.action = '/api/upload';
    rule.props.onSuccess = function (res, file) {
      // Must set file.url, otherwise form cannot get file data
      file.url = res.data.url;
      file.name = res.data.name;
    };
    rule.props.onError = function (err) {
      console.error('Upload failed:', err);
    };
  }
});

Use in Component:

vue
<template>
  <form-create :rule="rule" v-model:api="fApi" :option="options"/>
</template>

<script>
export default {
  data() {
    return {
      fApi: {},
      options: {
        // Form-level beforeFetch event for setting request headers
        beforeFetch: function (config, data) {
          // Get global token from external data
          const token = data.api.getData('globalToken');
          if (!config.headers) {
            config.headers = {};
          }
          config.headers.Authorization = 'Bearer ' + token;
          return config;
        }
      },
      rule: [
        {
          type: 'upload',
          field: 'upload1',
          title: 'Upload Image',
          props: {
            listType: 'picture-card'
            // action and onSuccess will be automatically set by Parser
          }
        },
        {
          type: 'upload',
          field: 'upload2',
          title: 'Upload File',
          props: {
            action: '/custom-upload',  // This will be overridden by Parser to '/api/upload'
            onSuccess: function (res, file) {
              console.log('Custom handling');  // This will be overridden by Parser
            }
          }
        }
      ]
    }
  }
}
</script>

Method 2: Use option.global Normal Configuration ​

Use option.global to set global configuration, which only takes effect when the rule doesn't define the corresponding property:

vue
<template>
  <form-create :rule="rule" v-model:api="fApi" :option="options"/>
</template>

<script>
export default {
  data() {
    return {
      fApi: {},
      options: {
        // Form-level beforeFetch event
        beforeFetch: function (config, data) {
          const token = data.api.getData('globalToken');
          if (!config.headers) {
            config.headers = {};
          }
          config.headers.Authorization = 'Bearer ' + token;
          return config;
        },
        global: {
          upload: {
            props: {
              // Only takes effect when action is not defined in rule
              action: '/api/upload',
              // Only takes effect when onSuccess is not defined in rule
              onSuccess: function (res, file) {
                file.url = res.data.url;
                file.name = res.data.name;
              },
              onError: function (err) {
                console.error('Upload failed:', err);
              }
            }
          }
        }
      },
      rule: [
        {
          type: 'upload',
          field: 'upload1',
          title: 'Upload Image',
          props: {
            listType: 'picture-card'
            // action and onSuccess not defined, will use global configuration
          }
        },
        {
          type: 'upload',
          field: 'upload2',
          title: 'Upload File',
          props: {
            action: '/custom-upload',  // action defined in rule, global configuration won't take effect
            onSuccess: function (res, file) {
              console.log('Custom handling');  // onSuccess defined in rule, global configuration won't take effect
            }
          }
        }
      ]
    }
  }
}
</script>

Method 3: Use option.global.deep Forced Override ​

Use the deep property, specify properties to forcibly override through dot notation paths, which will forcibly override properties with the same name in rules:

vue
<template>
  <form-create :rule="rule" v-model:api="fApi" :option="options"/>
</template>

<script>
export default {
  data() {
    return {
      fApi: {},
      options: {
        // Form-level beforeFetch event
        beforeFetch: function (config, data) {
          const token = data.api.getData('globalToken');
          if (!config.headers) {
            config.headers = {};
          }
          config.headers.Authorization = 'Bearer ' + token;
          return config;
        },
        global: {
          upload: {
            // Deep merge configuration: use dot notation paths to specify properties to override
            deep: {
              'props.action': '/api/upload',  // Forcibly override action in rule
              'props.onSuccess': function (res, file) {
                // Forcibly override onSuccess in rule
                file.url = res.data.url;
                file.name = res.data.name;
              },
              'props.onError': function (err) {
                console.error('Unified upload failure handling:', err);
              }
            }
          }
        }
      },
      rule: [
        {
          type: 'upload',
          field: 'upload1',
          title: 'Upload Image',
          props: {
            action: '/old-upload',  // This will be overridden by global configuration to '/api/upload'
            onSuccess: function (res, file) {
              console.log('Custom handling');  // This will be overridden by global configuration
            }
          }
        },
        {
          type: 'upload',
          field: 'upload2',
          title: 'Upload File',
          props: {
            // action and onSuccess not defined, will use global configuration
          }
        }
      ]
    }
  }
}
</script>

Set Global beforeFetch Event ​

beforeFetch is a form-level event configured in option, not in the component's props. This event triggers before all upload requests, suitable for unified setting of request headers, modifying request parameters, etc.

vue
<template>
  <form-create :rule="rule" v-model:api="fApi" :option="options"/>
</template>

<script>
export default {
  data() {
    return {
      fApi: {},
      options: {
        // Global beforeFetch event, all upload requests will trigger
        beforeFetch: function (config, data) {
          // Get global token from external data
          const token = data.api.getData('globalToken') || 
                       data.api.getData('$cookie.token') || 
                       '';

                       // Set request headers
          if (!config.headers) {
            config.headers = {};
          }
          config.headers.Authorization = 'Bearer ' + token;
          config.headers['X-Requested-With'] = 'XMLHttpRequest';

          // Can modify upload address
          // config.url = '/api/custom-upload';

          // Can add additional request parameters
          // config.data = {
          //   ...config.data,
          //   category: 'image'
          // };

          return config;
        }
      },
      rule: [
        {
          type: 'upload',
          field: 'upload1',
          title: 'Upload Image',
          props: {
            action: '/api/upload'
            // beforeFetch will automatically trigger before upload
          }
        }
      ]
    }
  },
  mounted() {
    // Set global token for beforeFetch to use
    this.$formCreate.setData({
      globalToken: 'your-token-here'
    });
  }
}
</script>

Usage Recommendations

  • Parser Configuration: Suitable for scenarios requiring forced unification of all upload component configurations, executes earliest, will override configurations in rules
  • Normal Configuration (option.global): Suitable for scenarios requiring default values for unconfigured upload components, won't override existing configurations in rules
  • Deep Merge Configuration (option.global.deep): Suitable for scenarios requiring forced override of configurations in rules, even if corresponding properties are already defined in rules
  • beforeFetch Event: Suitable for scenarios requiring unified setting of request headers, modifying request parameters, etc., configure at form level

Configuration Items ​

The upload component provides rich configuration options. Customize upload component behavior by configuring properties in the designer.

Property NameTypeDefault ValueRequiredDescription
disabledBoolean-NoWhether disabled
listTypeStringpicture-cardNoFile list type (text/picture/picture-card)
multipleBoolean-NoWhether to support multi-file upload
nameString-NoUploaded file field name
acceptString-NoAccepted file types for upload
actionString/NoUpload address
beforeUploadFunction-NoHook before uploading file
beforeRemoveFunction-NoHook before removing file
onSuccessFunction-NoHook when file upload succeeds
headersObject-NoSet upload request headers
dataObject-NoAdditional parameters attached when uploading
withCredentialsBoolean-NoSupport sending cookie credential information
autoUploadBooleantrueNoWhether to auto-upload
limitNumber-NoMaximum number of uploads allowed

Important Notes:

  • listType: Sets the display method of uploaded file list, picture-card is suitable for image uploads
  • onSuccess: Must set file.url in this callback, otherwise the form cannot get file data
  • accept: Can be set to file types (such as image/*, .pdf, etc.) to limit upload file types
  • action: Upload interface address, can be a complete URL or relative path

Events ​

The upload component provides rich events for listening to upload status changes and executing corresponding handling.

Event NameParametersDescription
changefile, fileListHook when file status changes
removefile, fileListHook when file is removed from file list
previewfileHook when clicking uploaded file in file list
errorerror, file, fileListHook when upload fails
progressevent, file, fileListHook during upload progress
exceedfiles, fileListHook when file count exceeds limit

Methods ​

The upload component provides various internal methods for handling file upload operations.

Method NameParametersDescriptionReturn Value
clearFiles-Clear uploaded file list-
abortfileCancel upload-
submit-Manually upload file list-

Method Usage Example ​

Clear File List:

js
function clearUpload($inject) {
    const uploadInstance = $inject.api.el('ref_F2vulxvqc841dac');
    uploadInstance.clearFiles();
}

Notes ​

  1. Must set file.url: In the onSuccess callback, set file.url = res.data.url, otherwise the form cannot get file information when submitting.

  2. beforeFetch Event: To add upload request headers (such as authentication token), set it in the form's beforeFetch event, not in the component's headers property.

  3. Configuration Differences Between UI Frameworks: element-plus and ant-design-vue have differences in upload component configuration. See the corresponding documentation based on the UI framework you use: