vant/src/uploader

Uploader

Intro

Used to upload a local image or file to the server and display a preview image and upload progress during the upload process. The Uploader component does not currently contain the interface logic for uploading files to the server, this step needs to be implemented by the user.

Install

Register component globally via app.use, refer to Component Registration for more registration ways.

import { createApp } from 'vue';
import { Uploader } from 'vant';

const app = createApp();
app.use(Uploader);

Usage

Basic Usage

<van-uploader :after-read="afterRead" />
export default {
  setup() {
    const afterRead = (file) => {
      console.log(file);
    };

    return {
      afterRead,
    };
  },
};

Preview File

<van-uploader v-model="fileList" multiple />
import { ref } from 'vue';

export default {
  setup() {
    const fileList = ref([
      { url: 'https://img.yzcdn.cn/vant/leaf.jpg' },
      { url: 'https://cloud-image', isImage: true },
    ]);

    return {
      fileList,
    };
  },
};

Upload Status

<van-uploader v-model="fileList" :after-read="afterRead" />
import { ref } from 'vue';

export default {
  setup() {
    const fileList = ref([
      {
        url: 'https://img.yzcdn.cn/vant/leaf.jpg',
        status: 'uploading',
        message: 'Uploading...',
      },
      {
        url: 'https://img.yzcdn.cn/vant/tree.jpg',
        status: 'failed',
        message: 'Failed',
      },
    ]);

    const afterRead = (file) => {
      file.status = 'uploading';
      file.message = 'Uploading...';

      setTimeout(() => {
        file.status = 'failed';
        file.message = 'Failed';
      }, 1000);
    };

    return {
      fileList,
      afterRead,
    };
  },
};

Max Count

<van-uploader v-model="fileList" multiple :max-count="2" />
import { ref } from 'vue';

export default {
  setup() {
    const fileList = ref([]);

    return {
      fileList,
    };
  },
};

Max Size

<van-uploader multiple :max-size="500 * 1024" @oversize="onOversize" />
import { Toast } from 'vant';

export default {
  setup() {
    const onOversize = (file) => {
      console.log(file);
      Toast('File size cannot exceed 500kb');
    };

    return {
      onOversize,
    };
  },
};

If you need to make different size limits for different types of files, you can pass a function to the max-size props.

<van-uploader multiple :max-size="isOverSize" />
import { Toast } from 'vant';

export default {
  setup() {
    const isOverSize = (file) => {
      const maxSize = file.type === 'image/jpeg' ? 500 * 1024 : 1000 * 1024;
      return file.size >= maxSize;
    };
    return {
      isOverSize,
    };
  },
};

Custom Upload Area

<van-uploader>
  <van-button icon="plus" type="primary">Upload Image</van-button>
</van-uploader>

Preview Cover

<van-uploader v-model="fileList">
  <template #preview-cover="{ file }">
    <div class="preview-cover van-ellipsis">{{ file.name }}</div>
  </template>
</van-uploader>

<style>
  .preview-cover {
    position: absolute;
    bottom: 0;
    box-sizing: border-box;
    width: 100%;
    padding: 4px;
    color: #fff;
    font-size: 12px;
    text-align: center;
    background: rgba(0, 0, 0, 0.3);
  }
</style>

Before Read

<van-uploader :before-read="beforeRead" />
import { Toast } from 'vant';

export default {
  setup() {
    // 返回布尔值
    const beforeRead = (file) => {
      if (file.type !== 'image/jpeg') {
        Toast('Please upload an image in jpg format');
        return false;
      }
      return true;
    };

    // 返回 Promise
    const asyncBeforeRead = (file) =>
      new Promise((resolve, reject) => {
        if (file.type !== 'image/jpeg') {
          Toast('Please upload an image in jpg format');
          reject();
        } else {
          const img = new File(['foo'], 'bar.jpg', {
            type: 'image/jpeg',
          });
          resolve(img);
        }
      });

    return {
      beforeRead,
      asyncBeforeRead,
    };
  },
};

Disable Uploader

Use disabled prop to disable uploader.

<van-uploader disabled />

Customize Single Preview Image Style

<van-uploader v-model="fileList" :deletable="false" />
import { ref } from 'vue';
import { Toast } from 'vant';

export default {
  setup() {
    const fileList = ref([
      { url: 'https://img.yzcdn.cn/vant/leaf.jpg' },
      {
        url: 'https://img.yzcdn.cn/vant/sand.jpg',
        deletable: true,
        beforeDelete: () => {
          Toast('Customize the events and styles of a single preview image');
        },
      },
      {
        url: 'https://img.yzcdn.cn/vant/tree.jpg',
        deletable: true,
        imageFit: 'contain',
        previewSize: 120,
      },
    ]);

    return { fileList };
  },
};

API

Props

Attribute Description Type Default
v-model List of uploaded files FileListItem[] -
accept Accepted file type string image/*
name Input name number | string -
preview-size Size of preview image number | string 80px
preview-image Whether to show image preview boolean true
preview-full-image Whether to show full screen image preview when image is clicked boolean true
preview-options Options of full screen image previewsee ImagePreview object -
multiple Whether to enable multiple selection pictures boolean false
disabled Whether to disabled the upload boolean false
readonly v3.1.5 Whether to make upload area readonly boolean false
deletable Whether to show delete icon boolean true
show-upload Whether to show upload area boolean true
lazy-load Whether to enable lazy loadshould register Lazyload component boolean false
capture Capturecan be set to camera string -
after-read Hook after reading the file Function -
before-read Hook before reading the file, return false to stop reading the file, can return Promise Function -
before-delete Hook before delete the file, return false to stop reading the file, can return Promise Function -
max-size v3.0.17 Max size of file number | string | (file: File) => boolean -
max-count Max count of image number | string -
result-type Type of file read result, can be set to file text string dataUrl
upload-text Upload text string -
image-fit Preview image fit mode string cover
upload-icon Upload icon string photograph

Tips: accept, capture and multiple are the attributes of the native input tag, there may be some compatibility issues under different systems and WebView.

Events

Event Description Arguments
oversize Emitted when file size over limit Same as after-read
click-upload v3.1.5 Emitted when click upload area event: MouseEvent
click-preview Emitted when preview image is clicked Same as after-read
close-preview Emitted when the full screen image preview is closed -
delete Emitted when preview file is deleted Same as after-read

Slots

Name Description SlotProps
default Custom icon -
preview-cover Custom content that covers the image preview item: FileListItem

Parameters of before-read、after-read、before-delete

Attribute Description Type
file File object object
detail Detail info, contains name and index object

ResultType

Value Description
file Result contains File object
text Result contains File object and text content
dataUrl Result contains File object and base64 content

Methods

Use ref to get Uploader instance and call instance methods.

Name Description Attribute Return value
closeImagePreview Close full screen image preview - -
chooseFile Trigger choosing files, works with the user action context only because of browser security - -

Types

Get the type definition of the Uploader instance through UploaderInstance.

import { ref } from 'vue';
import type { UploaderInstance } from 'vant';

const uploaderRef = ref<UploaderInstance>();

uploaderRef.value?.chooseFile();

CSS Variables

The component provides the following CSS variables, which can be used to customize styles. Please refer to ConfigProvider component.

Name Default Value Description
--van-uploader-size 80px -
--van-uploader-icon-size 24px -
--van-uploader-icon-color var(--van-gray-4) -
--van-uploader-text-color var(--van-gray-6) -
--van-uploader-text-font-size var(--van-font-size-sm) -
--van-uploader-upload-background-color var(--van-gray-1) -
--van-uploader-upload-active-color var(--van-active-color) -
--van-uploader-delete-color var(--van-white) -
--van-uploader-delete-icon-size 14px -
--van-uploader-delete-background-color rgba(0, 0, 0, 0.7) -
--van-uploader-file-background-color var(--van-background-color) -
--van-uploader-file-icon-size 20px -
--van-uploader-file-icon-color var(--van-gray-7) -
--van-uploader-file-name-padding 0 var(--van-padding-base) -
--van-uploader-file-name-margin-top var(--van-padding-xs) -
--van-uploader-file-name-font-size var(--van-font-size-sm) -
--van-uploader-file-name-text-color var(--van-gray-7) -
--van-uploader-mask-text-color var(--van-white) -
--van-uploader-mask-background-color fade(var(--van-gray-8), 88%) -
--van-uploader-mask-icon-size 22px -
--van-uploader-mask-message-font-size var(--van-font-size-sm) -
--van-uploader-mask-message-line-height var(--van-line-height-xs) -
--van-uploader-loading-icon-size 22px -
--van-uploader-loading-icon-color var(--van-white) -
--van-uploader-disabled-opacity var(--van-disabled-opacity) -