import{o as a,a as t,y as e}from"./vue-libs.b44bc779.js";const n={class:"van-doc-markdown-body"},l=e(`

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://fastly.jsdelivr.net/npm/@vant/assets/leaf.jpeg' },
      { 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://fastly.jsdelivr.net/npm/@vant/assets/leaf.jpeg',
        status: 'uploading',
        message: 'Uploading...',
      },
      {
        url: 'https://fastly.jsdelivr.net/npm/@vant/assets/tree.jpeg',
        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>

Preview Size

Using preview-size prop to custom the size of preview image.

<!-- The default unit is px -->
<van-uploader v-model="fileList" preview-size="60" />
<!-- Support other units, such as rem, vh, vw -->
<van-uploader v-model="fileList" preview-size="5rem" />

You can set the width and height separately.

<van-uploader v-model="fileList" :preview-size="[60, 40]" />

Before Read

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

export default {
  setup() {
    // \u8FD4\u56DE\u5E03\u5C14\u503C
    const beforeRead = (file) => {
      if (file.type !== 'image/jpeg') {
        Toast('Please upload an image in jpg format');
        return false;
      }
      return true;
    };

    // \u8FD4\u56DE 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://fastly.jsdelivr.net/npm/@vant/assets/sand.jpeg',
        deletable: true,
        beforeDelete: () => {
          Toast('Customize the events and styles of a single preview image');
        },
      },
      {
        url: 'https://fastly.jsdelivr.net/npm/@vant/assets/tree.jpeg',
        imageFit: 'contain',
      },
    ]);

    return { fileList };
  },
};

API

Props

AttributeDescriptionTypeDefault
v-modelList of uploaded filesFileListItem[]-
acceptAccepted file typestringimage/*
nameInput name, usually a unique string or numbernumber | string-
preview-sizeSize of preview imagenumber | string | Array80px
preview-imageWhether to show image previewbooleantrue
preview-full-imageWhether to show full screen image preview when image is clickedbooleantrue
preview-optionsOptions of full screen image preview, see ImagePreviewobject-
multipleWhether to enable multiple selection picturesbooleanfalse
disabledWhether to disabled the uploadbooleanfalse
readonly v3.1.5Whether to make upload area readonlybooleanfalse
deletableWhether to show delete iconbooleantrue
show-uploadWhether to show upload areabooleantrue
lazy-loadWhether to enable lazy load, should register Lazyload componentbooleanfalse
captureCapture, can be set to camerastring-
after-readHook after reading the fileFunction-
before-readHook before reading the file, return false to stop reading the file, can return PromiseFunction-
before-deleteHook before delete the file, return false to stop reading the file, can return PromiseFunction-
max-size v3.0.17Max size of filenumber | string | (file: File) => booleanInfinity
max-countMax count of imagenumber | stringInfinity
result-typeType of file read result, can be set to file textstringdataUrl
upload-textUpload textstring-
image-fitPreview image fit modestringcover
upload-iconUpload iconstringphotograph

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

EventDescriptionArguments
oversizeEmitted when file size over limitSame as after-read
click-upload v3.1.5Emitted when click upload areaevent: MouseEvent
click-previewEmitted when preview image is clickedSame as after-read
close-previewEmitted when the full screen image preview is closed-
deleteEmitted when preview file is deletedSame as after-read

Slots

NameDescriptionSlotProps
defaultCustom upload area-
preview-delete v.3.5.0Custom delete iconitem: FileListItem
preview-coverCustom content that covers the image previewitem: FileListItem

Parameters of before-read\u3001after-read\u3001before-delete

AttributeDescriptionType
fileFile objectobject
detailDetail info, contains name and indexobject

ResultType

ValueDescription
fileResult contains File object
textResult contains File object and text content
dataUrlResult contains File object and base64 content

Methods

Use ref to get Uploader instance and call instance methods.

NameDescriptionAttributeReturn value
closeImagePreviewClose full screen image preview--
chooseFileTrigger choosing files, works with the user action context only because of browser security--

Types

The component exports the following type definitions:

import type {
  UploaderProps,
  UploaderInstance,
  UploaderResultType,
  UploaderFileListItem,
} from 'vant';

UploaderInstance is the type of component instance:

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

const uploaderRef = ref<UploaderInstance>();

uploaderRef.value?.chooseFile();

Theming

CSS Variables

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

NameDefault ValueDescription
--van-uploader-size80px-
--van-uploader-icon-size24px-
--van-uploader-icon-colorvar(--van-gray-4)-
--van-uploader-text-colorvar(--van-text-color-2)-
--van-uploader-text-font-sizevar(--van-font-size-sm)-
--van-uploader-upload-background-colorvar(--van-gray-1)-
--van-uploader-upload-active-colorvar(--van-active-color)-
--van-uploader-delete-colorvar(--van-white)-
--van-uploader-delete-icon-size14px-
--van-uploader-delete-background-colorrgba(0, 0, 0, 0.7)-
--van-uploader-file-background-colorvar(--van-background-color)-
--van-uploader-file-icon-size20px-
--van-uploader-file-icon-colorvar(--van-gray-7)-
--van-uploader-file-name-padding0 var(--van-padding-base)-
--van-uploader-file-name-margin-topvar(--van-padding-xs)-
--van-uploader-file-name-font-sizevar(--van-font-size-sm)-
--van-uploader-file-name-text-colorvar(--van-gray-7)-
--van-uploader-mask-text-colorvar(--van-white)-
--van-uploader-mask-background-colorfade(var(--van-gray-8), 88%)-
--van-uploader-mask-icon-size22px-
--van-uploader-mask-message-font-sizevar(--van-font-size-sm)-
--van-uploader-mask-message-line-heightvar(--van-line-height-xs)-
--van-uploader-loading-icon-size22px-
--van-uploader-loading-icon-colorvar(--van-white)-
--van-uploader-disabled-opacityvar(--van-disabled-opacity)-
`,25),p=[l],h={__name:"README",setup(d,{expose:s}){return s({frontmatter:{}}),(o,c)=>(a(),t("div",n,p))}};export{h as default};