注: 本文中所有的原始文件对象统称为原始文件,而经过包装后的文件对象称为文件对象,这个文件对象的结构如下:

    基本用法

    1. export default {
    2. methods: {
    3. filesAdded(files) {
    4. let hasIgnore = false
    5. const maxSize = 1 * 1024 * 1024 // 1M
    6. for (let k in files) {
    7. const file = files[k]
    8. if (file.size > maxSize) {
    9. file.ignore = true
    10. hasIgnore = true
    11. }
    12. }
    13. hasIgnore && this.- createToast({
    14. type: 'warn',
    15. time: 1000,
    16. }).show()
    17. }
    18. }
    19. }

    配置 action 表示上传的 URL 地址,而 simultaneous-uploads 则表示支持的并发上传个数。

    通过 files-added 事件可以实现文件过滤,设置 file.ignore = true 即可。

    压缩图片且通过 Base64 上传

    1. import compress from '../../modules/image'
    2. export default {
    3. data() {
    4. return {
    5. target: '//jsonplaceholder.typicode.com/photos/',
    6. prop: 'base64Value'
    7. }
    8. }
    9. },
    10. methods: {
    11. processFile(file, next) {
    12. compress(file, {
    13. compress: {
    14. width: 1600,
    15. height: 1600,
    16. quality: 0.5
    17. }
    18. }, next)
    19. },
    20. file.base64Value = file.file.base64
    21. }
    22. }
    23. }

    process-file 则是一个函数,主要用于处理原生文件的,调用 next 回调的话,参数是处理完的文件对象,这里示例的就是调用 compress 做压缩,处理完后会回调 next。

    file-submitted 事件则是每个文件处理完后添加到 upload 实例的 files 数组中后触发,参数就是一个处理后的文件对象。

    自定义结构样式

    使用默认插槽来实现自定义结构,在此基础上自定义样式。

    1. export default {
    2. data() {
    3. return {
    4. action: '//jsonplaceholder.typicode.com/photos/',
    5. }
    6. },
    7. methods: {
    8. addedHandler() {
    9. const file = this.files[0]
    10. file && this.- refs.upload.removeFile(file)
    11. },
    12. errHandler(file) {
    13. // const msg = file.response.message
    14. this.- createToast({
    15. type: 'warn',
    16. txt: 'Upload fail',
    17. time: 1000
    18. }).show()
    19. }
    20. }

    上述示例实现的效果就是点击上传(一次只能选择一张)一张图片,此图片就会直接展示,而上传按钮本身则是不可见,覆盖在图片预览区域上。再次重新选择图片,就会移除掉上次选择的图片,重新展示新选择的图片。

    action 子配置项

    如果 action 是字符串,则会被处理成 { target: action } 这样结构。

    processFile 子配置项

    一个函数,这个函数有两个参数:(file, next)file 就是原始文件,next 为处理完毕后的回调函数,调用的时候需要传入处理后的文件。

    https://didi.github.io/cube-ui/#/zh-CN/docs/upload