VEUI

VEUI on GitHub
Play!中文

Uploader

Examples

File upload

Set the value of type to file to enter file upload mode.

Normal size

  • demo-file1.txt
  • demo-file2.txt

Small size

  • demo-file1.txt
  • demo-file2.txt
Edit this demo on GitHubEdit
<template>
<article>
  <section>
    <h4>Normal size</h4>
    <veui-uploader
      v-model="files"
      action="/api/upload"
    />
  </section>
  <section>
    <h4>Small size</h4>
    <veui-uploader
      v-model="files2"
      action="/api/upload"
      ui="s"
    />
  </section>
</article>
</template>

<script>
import { Uploader } from 'veui'
import { cloneDeep } from 'lodash'

export default {
  components: {
    'veui-uploader': Uploader
  },
  data () {
    let files = [
      {
        name: 'demo-file1.txt',
        src: '/file/demo-file1.txt',
        key: 0
      },
      {
        name: 'demo-file2.txt',
        src: '/file/demo-file2.txt',
        key: 1
      }
    ]
    return {
      files,
      files2: cloneDeep(files)
    }
  }
}
</script>

<style lang="less" scoped>
article {
  display: flex;
}

section {
  width: 45%;
}
</style>

Image upload

Set the value of type to image to enter image upload mode.

Normal size

  • Normal size

Small size

  • Small size
Edit this demo on GitHubEdit
<template>
<article>
  <section>
    <h4>Normal size</h4>
    <veui-uploader
      v-model="images"
      type="image"
      action="/api/upload"
    >
      <template #help>
        Normal size
      </template>
    </veui-uploader>
  </section>
  <section>
    <h4>Small size</h4>
    <veui-uploader
      v-model="images2"
      type="image"
      action="/api/upload"
      ui="s"
    >
      <template #help>
        Small size
      </template>
    </veui-uploader>
  </section>
</article>
</template>

<script>
import { Uploader } from 'veui'
import { cloneDeep } from 'lodash'

export default {
  components: {
    'veui-uploader': Uploader
  },
  data () {
    let images = [
      {
        src: '/images/development/uploader/demo-image1.jpg',
        key: 0
      },
      {
        src: '/images/development/uploader/demo-image2.jpg',
        key: 1
      }
    ]
    return {
      images,
      images2: cloneDeep(images)
    }
  }
}
</script>

Media upload

Set the value of type to media to enter media upload mode.

Normal size

  • Normal size

Small size

  • Small size
Edit this demo on GitHubEdit
<template>
<article>
  <section>
    <h4>Normal size</h4>
    <veui-uploader
      v-model="media"
      type="media"
      action="/api/upload"
    >
      <template #help>
        Normal size
      </template>
    </veui-uploader>
  </section>
  <section>
    <h4>Small size</h4>
    <veui-uploader
      v-model="media2"
      type="media"
      action="/api/upload"
      ui="s"
    >
      <template #help>
        Small size
      </template>
    </veui-uploader>
  </section>
</article>
</template>

<script>
import { Uploader } from 'veui'
import { cloneDeep } from 'lodash'

export default {
  components: {
    'veui-uploader': Uploader
  },
  data () {
    let media = [
      {
        type: 'image',
        src: '/images/development/uploader/demo-image1.jpg',
        key: 0
      },
      {
        type: 'video',
        src: 'https://nadvideo2.baidu.com/5dafd8544f4f53b27a5f59b0ab780403_1920_1080.mp4',
        poster: 'https://feed-image.baidu.com/0/pic/4dced79d185a16e228652b136f653dcc.jpg',
        key: 1
      }
    ]
    return {
      media,
      media2: cloneDeep(media)
    }
  }
}
</script>

Validation

Validate image format, size, quantity, and use validator for custom validation.

  • 请选择jpg、png图片,大小不超过100kb,宽高分别大于200px,最多上传6张图片
Edit this demo on GitHubEdit
<template>
<article>
  <section>
    <veui-uploader
      v-model="images"
      type="image"
      action="/api/upload"
      accept="jpg,png"
      :max-count="6"
      max-size="100kb"
      :validator="validator"
    >
      <template #help>
        请选择jpg、png图片,大小不超过100kb,宽高分别大于200px,最多上传6张图片
      </template>
    </veui-uploader>
  </section>
</article>
</template>

<script>
import { Uploader } from 'veui'

export default {
  components: {
    'veui-uploader': Uploader
  },
  data () {
    return {
      images: [
        {
          src: '/images/development/uploader/demo-image1.jpg',
          key: 0
        },
        {
          src: '/images/development/uploader/demo-image2.jpg',
          key: 1
        }
      ],
      validator (file) {
        return new Promise(resolve => {
          let image = new Image()
          image.src = window.URL.createObjectURL(file)
          image.onload = () => {
            resolve({
              valid: image.height > 200 && image.width > 200,
              message: '图片宽高太小'
            })
          }
        })
      }
    }
  }
}
</script>

Custom upload

Customize the upload process using upload and configure the overlay options using controls.

  • 点击图片浮层上的向右箭头按钮改变图片位置
Edit this demo on GitHubEdit
<template>
<article>
  <section>
    <veui-uploader
      v-model="images"
      type="image"
      :action="action"
      :controls="controls"
      request-mode="custom"
      :upload="upload"
      @moveright="handleMoveRight"
    >
      <template #help>
        点击图片浮层上的向右箭头按钮改变图片位置
      </template>
    </veui-uploader>
  </section>
</article>
</template>

<script>
import { Uploader } from 'veui'

export default {
  components: {
    'veui-uploader': Uploader
  },
  data () {
    return {
      action: '/upload',
      images: [
        {
          key: 0,
          src: '/images/development/uploader/demo-image1.jpg'
        },
        {
          key: 1,
          src: '/images/development/uploader/demo-image2.jpg'
        }
      ],
      controls (file, defaultControls) {
        if (file.status === 'success') {
          return [
            { name: 'moveright', icon: 'chevron-right', disabled: false },
            ...defaultControls
          ]
        }
        return defaultControls
      },
      upload: (file, { onload, onprogress, onerror }) => {
        let xhr = new XMLHttpRequest()
        file.xhr = xhr

        xhr.upload.onprogress = e => onprogress(e)
        xhr.onload = e => {
          try {
            onload(JSON.parse(xhr.responseText))
          } catch (e) {
            onload({ success: false, message: e })
          }
        }
        xhr.onerror = e => onerror(e)
        let formData = new FormData()
        formData.append('file', file)

        xhr.open('POST', this.action, true)
        xhr.send(formData)

        return () => {
          xhr.abort()
        }
      }
    }
  },
  methods: {
    handleMoveRight (file, index) {
      if (index < this.images.length - 1) {
        let temp = { ...this.images[index] }
        this.$set(this.images, index, this.images[index + 1])
        this.$set(this.images, index + 1, temp)
      }
    }
  }
}
</script>

Sorting

Set the sortable property to specify that upload items can be sorted by drag and drop.

Edit this demo on GitHubEdit
<template>
<article>
  <section>
    <veui-uploader
      v-model="images"
      sortable
      type="image"
      action="/api/upload"
    />
  </section>
</article>
</template>

<script>
import { Uploader } from 'veui'

export default {
  components: {
    'veui-uploader': Uploader
  },
  data () {
    return {
      images: [
        {
          key: 0,
          src: '/images/development/uploader/demo-image1.jpg'
        },
        {
          key: 1,
          src: '/images/development/uploader/demo-image2.jpg'
        }
      ]
    }
  }
}
</script>

Custom action bar

Set the controls property to specify the action options that appear when hovering over each upload item.

Edit this demo on GitHubEdit
<template>
<article>
  <section>
    <veui-uploader
      v-model="images"
      :controls="controls"
      type="image"
      action="/api/upload"
      @star="handleStar"
    />
  </section>
</article>
</template>

<script>
import { Uploader, toast } from 'veui'
import 'veui-theme-dls-icons/star'

export default {
  components: {
    'veui-uploader': Uploader
  },
  data () {
    return {
      images: [
        {
          key: 0,
          src: '/images/development/uploader/demo-image1.jpg'
        },
        {
          key: 1,
          src: '/images/development/uploader/demo-image2.jpg'
        }
      ],
      controls (item, defaultControls) {
        return [
          ...defaultControls,
          {
            name: 'star',
            icon: 'star',
            label: 'star'
          }
        ]
      }
    }
  },
  methods: {
    handleStar () {
      toast.info('You click star!')
    }
  }
}
</script>

Custom upload entry

Set the entries property to specify the action options that appear when hovering over "continue uploading" items.

Edit this demo on GitHubEdit
<template>
<article>
  <section>
    <veui-uploader
      v-model="images"
      :entries="entries"
      type="image"
      action="/api/upload"
      @star="handleStar"
    />
  </section>
</article>
</template>

<script>
import { Uploader, toast } from 'veui'
import 'veui-theme-dls-icons/star'

export default {
  components: {
    'veui-uploader': Uploader
  },
  data () {
    return {
      images: [
        {
          key: 0,
          src: '/images/development/uploader/demo-image1.jpg'
        },
        {
          key: 1,
          src: '/images/development/uploader/demo-image2.jpg'
        }
      ],
      entries (defaultEntries) {
        return [
          ...defaultEntries,
          {
            name: 'star',
            icon: 'star',
            label: 'star'
          }
        ]
      }
    }
  },
  methods: {
    handleStar () {
      toast.info('You clicked star!')
    }
  }
}
</script>

Custom pick

Set the pick property to customize file selection.

    Edit this demo on GitHubEdit
    <template>
    <article>
      <section>
        <veui-uploader
          type="file"
          :pick="pick"
          action="/api/upload"
        />
      </section>
    </article>
    </template>
    
    <script>
    import { Uploader } from 'veui'
    import confirm from 'veui/plugins/confirm'
    import Vue from 'vue'
    
    Vue.use(confirm)
    
    export default {
      components: {
        'veui-uploader': Uploader
      },
      methods: {
        pick ({ remainingCount }) {
          return this.$confirm('模拟自定义选择文件', '确认').then((ready) => {
            return ready
              ? new File([`count: ${remainingCount}`], 'pick.txt', { type: 'text/plain' })
              : null
          })
        }
      }
    }
    </script>
    

    Help text

    Set the help property or help slot to specify help text.

    辅助信息位置:
    Help text
    • demo-file1.txt
    Custom help text via `help` slot
    • demo-file1.txt
    Edit this demo on GitHubEdit
    <template>
    <article>
      <section>
        <div>
          辅助信息位置:
          <veui-radio-button-group
            v-model="helpPosition"
            ui="s"
            :items="availableHelpPositions"
          />
        </div>
        <veui-uploader
          v-model="files"
          class="uploader"
          :help-position="helpPosition"
          help="Help text"
          action="/api/upload"
        />
        <veui-uploader
          v-model="files"
          class="uploader"
          :help-position="helpPosition"
          action="/api/upload"
        >
          <template #help>
            Custom help text via `help` slot
          </template>
        </veui-uploader>
      </section>
    </article>
    </template>
    
    <script>
    import { Uploader, RadioButtonGroup } from 'veui'
    
    const mapper = (value) => ({ label: value, value })
    
    export default {
      components: {
        'veui-uploader': Uploader,
        'veui-radio-button-group': RadioButtonGroup
      },
      data () {
        let files = [
          {
            name: 'demo-file1.txt',
            src: '/file/demo-file1.txt',
            key: 0
          }
        ]
        return {
          files,
          helpPosition: 'side',
          availableHelpPositions: ['side', 'bottom'].map(mapper)
        }
      }
    }
    </script>
    
    <style lang="less" scoped>
    article {
      display: flex;
    }
    
    .uploader {
      margin-top: 16px;
    }
    
    section {
      width: 45%;
    }
    </style>
    

    API

    Props

    NameTypeDefaultDescription
    uistring-

    Predefined styles.

    ValueDescription
    sSmall-sized style.
    mMedium-sized style.
    typestring'file'

    The type of file to be uploaded.

    ValueDescription
    fileUpload files.
    imageUpload images.
    mediaUpload media files (supports both video and image).
    videoUpload videos.
    valueObject | Array<Object>-

    When multiple is set to true, returns an array of file objects. Additionally, if max-count is set to a value greater than 1, it is regarded as having enabled multiple.

    Each file object is of type {name: string, src: string, ...}, as well as custom properties added in convert-response.

    key-fieldstring'key'Specifies the unique key of the file object, which serves as the basis for correctly handling the order of the file list when the data changes.
    namestring'file'The name of the native <input> element.
    actionstring-The upload URL.
    headersObjectuploader.headersThe content to be added to the HTTP request headers. Can be globally configured.
    with-credentialsbooleantrueSame as the withCredentials property of XMLHttpRequest.
    request-modestringuploader.requestMode

    Specifies the asynchronous upload method. Can be globally configured.

    ValueDescription
    xhrUpload using XMLHttpRequest.
    iframeUpload using <iframe>.
    customCustom upload process, uploaded via the prop upload method.
    iframe-modestringuploader.iframeMode

    When the value of request-mode is iframe, specifies the callback method after the upload is successful. Can be globally configured.

    ValueDescription
    postmessageCallback via PostMessage.
    callbackCallback via calling the callback function in the window's callback-namespace.
    callback-namespacestringuploader.callbackNamespaceSpecifies the namespace of the callback function when request-mode is 'iframe' and iframe-mode is 'callback', under the window object. Can be globally configured.
    data-typestring'json'

    Specifies the parsing method for text if the callback value is text. data-type can be empty if the callback data is an Object.

    ValueDescription
    jsonThe text returned by the callback is JSON.
    textThe text returned by the callback is plain text.
    convert-responseuploader.convertResponse-

    A function that converts callback data to the required format so that the component can determine whether the upload was successful and display the corresponding result. The parameter is the callback data. The format of the returned result is as follows:

    NameTypeDescription
    successbooleanIndicates whether the upload was successful.
    namestringThe name of the file. Required when success is true.
    srcstringThe address of the file. Required when success is true.
    messagestringError message when upload fails. Required when success is false.
    previewbooleanWhether to preview the failed upload item when upload fails.

    Custom attributes can also be added to the returned result. These custom attributes will be included in the value and change, success, failure, remove, and progress event callback parameters file. Can be globally configured.

    acceptstring-Same as the accept attribute of the native <input> element, adding another layer of validation after the browser's file type filtering. For cases where the MIME type, such as application/msword, does not match the extension, the validation is skipped.
    max-countnumber-The maximum number of files.
    max-sizenumber | string-The maximum size of a single file. If it is a number, the unit is in bytes; if it is a string, it supports adding units after the number, and the units can be b / kb / mb / gb / tb.
    validatorfunction(Object): Object | Promise<Object>-

    Custom validation logic, with the original File object as the parameter. The format of the returned result is as follows:

    NameTypeDescription
    validbooleanWhether the validation passes.
    messagestringError message when valid is false.
    previewbooleanWhether to preview the failed upload item when validation fails.

    Asynchronous validation is supported, and the return value can be a Promise that resolves to the above return result.

    payloadObject-Additional parameters to be carried in the upload request.
    autouploadbooleantrueSpecifies whether to upload immediately after selecting files.
    orderstring'asc'

    The display order of uploaded files, sorted by the time of upload start.

    ValueDescription
    ascAscending order.
    descDescending order.
    picker-positionstring'after'

    In image upload mode, the position of the upload button in the image queue.

    ValueDescription
    beforeThe upload button is always at the front of the queue.
    afterThe upload button is always at the end of the queue.
    topThe upload button is always on top of the queue.
    noneDo not show the upload button.
    uploadfunction(Object, Object): function-

    Customize the upload process when the value of request-mode is 'custom'. The first parameter is the original File object, and the second parameter is the object containing the callback functions related to the upload process, with the following specific properties:

    NameTypeDescription
    onloadfunctionCallback function when the upload is complete, with the same content as the return value of the convert-response attribute.
    onprogressfunctionCallback function when the upload progress changes, with the parameter { loaded: number, total: number }, where loaded is the number of bytes uploaded, and total is the total number of bytes in the file.
    oncancelfunctionCallback function to be executed on the component when the custom upload is actively canceled, with no parameters.
    onerrorfunctionCallback function when an error occurs during the upload, with the parameter { message: string }, where message is the error message.

    If upload returns a function, that function will be called when the user cancels the operation or the upload component is destroyed, to interrupt the custom upload process.

    controlsfunction(Object, Array<Object>): Array<Object>-

    In image upload mode, customize the operation items on the image mask layer. The parameters are (file: Object, defaultControls: Array<Object>), where file is the file-related information, and defaultControls is the array containing the default operation items. Depending on the status of the file, return an array containing different operation items. The specific properties of each operation item are as follows:

    NameTypeDescription
    namestringThe name of the operation item. Clicking this button will trigger an event with the same name. The callback parameter of the event is (file: Object, index: number), where file is the file object that triggered the event, and index is the sequence number of the file in the list.
    labelstringThe text description of the operation item.
    iconstringThe icon used for the operation item.
    disabledbooleanWhether the operation item is disabled. If this field is empty, the disabled status of the operation item follows the overall disabled status of the component.
    multiplebooleanfalseUpload multiple files. When max-count is 1 and multiple is true, value is also an array.
    entriesfunction(Array<Object>): Array<Object>-

    Control the operation items for each uploaded file, such as delete and preview. The default operation item array will be passed as a parameter, and the actual effective operation item array will be returned. The operation item object refers to the field details of the controls attribute.

    pickfunction({remainingCount: number}): Promise<Object>-

    Custom logic for selecting files to be uploaded.

    function pick({ remainingCount: number }): Promise<PickedFile | PickedFile[]>
    
    type PickedFile = {
      name: string
      type: string
      src: string
      poster?: string
      alt?: string
      size?: number
    }
    
    ValueDescription
    nameFile name.
    typeFile type.
    srcFile address.
    posterPreview image for video files.
    altReplacement text.
    sizeFile size.
    after-pickfunction(Array<Object>): void-The callback after selecting files.
    sortablebooleanfalseWhether the file list can be sorted.
    preview-optionsobject{wrap: true, indicator: 'number'}Preview options passed to Lightbox.
    validity-display'popup' | 'inline''popup'

    Display method for validation information.

    ValueDescription
    popupDisplay validation information in a popup when hovering.
    inlineDisplay validation information inline.
    helpstring-Help text.
    help-position'side' | 'bottom''side'

    Display position for help information.

    ValueDescription
    sideDisplay next to the upload button.
    bottomDisplay below the upload button.
    picker-labelstring-The text of the upload button.
    picker-iconstring | Object-The icon of the upload button, referring to the name prop of Icon.

    Slots

    NameDescription
    uploadThe area of the upload button in image upload mode.
    helpTips for file quantity, format, size, etc.
    file

    The area of a single file used to customize its content.

    NameTypeDescription
    namestringThe name of the file.
    srcstringThe address of the file.
    statusstringThe status of the file. 'success' indicates a successful upload; 'uploading' indicates that the file is being uploaded; 'failure' indicates a failed upload.
    indexnumberThe serial number of the file in the list.
    file-beforeThe area before the content of a single file. The slot parameters are the same as those of the file slot.
    file-afterThe area after the content of a single file. The slot parameters are the same as those of the file slot.
    uploadingThe area of a single image being uploaded in image upload mode. The slot parameters are the same as those of the file slot.
    failureThe area of a single image that failed to upload in image upload mode. The slot parameters are the same as those of the file slot).

    Events

    NameDescription
    change

    Triggered only when uploading or deleting files, the callback parameter is (value).

    NameTypeDescription
    valueObject | Array<Object>The value of the component's value property.
    remove

    Triggered when a file is deleted, the callback parameter is (file, index).

    NameTypeDescription
    fileObject

    The file that was deleted.

    NameTypeDescription
    namestringThe name of the file.
    srcstringThe address of the file.
    statusstringThe upload status. 'success' indicates that the upload was successful; 'uploading' indicates that the upload is in progress; 'failure' indicates that the upload failed.
    indexnumberThe index of the deleted file.

    Also contains custom properties added in convert-response.

    successTriggered when uploading is successful, the callback parameter is the same as that of the remove event.
    failureTriggered when uploading fails, the callback parameter is the same as that of the remove event.
    invalid

    Triggered when file validation fails, the callback parameter is (validity: Object).

    NameTypeDescription
    fileObjectThe file information that did not pass validation, which is the same as the file parameter in the remove event callback. If the reason for the validation failure is that the selected number of files exceeds the max-count limit, this field is empty.
    errorsArray<Object>
    TypeDescriptionvalue Typevalue Description
    TYPE_INVALIDFile type validation failed.stringThe name of the file.
    SIZE_INVALIDFile size validation failed.numberThe size of the file in bytes.
    TOO_MANY_FILESThe number of selected files exceeds the max-count limit.numberThe number of files already selected.
    CUSTOM_INVALIDvalidator custom validation failed.ObjectThe file object, with the same fields as the file parameter in the remove event callback.
    statuschange

    Triggered when the overall status of all files changes, the callback parameter is the overall status of the component (status: string).

    ValueDescription
    emptyNo files have been selected for upload.
    uploadingAt least one file is currently being uploaded.
    failureAt least one file upload has failed.
    successAll files have been uploaded successfully.
    progress

    Triggered when the upload progress changes in the case where the value of request-mode is 'xhr', the callback parameter is (file, index, event).

    NameTypeDescription
    fileObjectThe same as the file parameter in the remove event callback.
    indexnumberThe index of the file currently being uploaded.
    eventEventThe native upload progress event.

    Methods

    NameDescription
    startUploadManually start uploading when autoupload is false.

    Configs

    KeyTypeDefaultDescription
    uploader.requestModestring'xhr'See request-mode prop.
    uploader.iframeModestring'postmessage'See iframe-mode prop.
    uploader.callbackNamespacestring'veuiUploadResult'See callback-namespace prop.
    uploader.headersObject-See headers prop.
    uploader.convertResponsefunction(Object): Object-See convert-response prop.
    uploader.pickerPositionstring'after'See picker-position prop.

    Icons

    NameDescription
    uploadUpload files.
    add-imageUpload images.
    clearDelete.
    successUpload succeeded.
    failureUpload failed.
    loadingUploading.
    fileUploaded files.
    alertValidation failure warning.
    previewPreview images.

    CSS

    NameTypeDefaultDescription
    --dls-uploader-file-item-width<length>-The width of file list item when type prop is set to file.
    Edit this page on GitHubEdit
    © Baidu, Inc. 2024