springboot + iview + upload实现图片上传

2,281 阅读1分钟

echo编辑整理,欢迎转载,转载请声明文章来源。欢迎添加echo微信(微信号:t2421499075)交流学习。 百战不败,依不自称常胜,百败不颓,依能奋力前行。——这才是真正的堪称强大!!!

该文主要用于upload实现记录,只是解析了upload的使用规则,熟悉的可以跳过。实现技术vue + iview

以iview中upload的一下样式为模板

在这里插入图片描述

实现代码

<Upload ref="upload"
    :max-size="2048"
    :format="['jpg','jpeg','png']"
    :on-remove="handleRemove"
    :on-success="handleSuccess"
    :on-exceeded-size="handleMaxSize"
    :on-format-error="handleFormatError"
    :before-upload="handleBeforeUpload"
    action="http://127.0.0.1:8080/springboot/upload/img">
    <Button icon="ios-cloud-upload-outline" style="margin-top: 5px">Upload files</Button>
</Upload>

# 校验文件格式对应的是一下两个属性
:format="['jpg','jpeg','png']"
:on-format-error="handleFormatError"

handleFormatError: function (file) {
    this.$Modal.info({
        title: '文件格式不正确',
        content: '文件 ' + file.name + ' 格式不正确,请上传 jpg、jpeg或 png 格式的图片。'
    });
},

# 校验文件大小对应的是一下两个属性
:max-size="2048" (对应的kb,这里最大只能上传2048k的文件)
:on-exceeded-size="handleMaxSize"

handleMaxSize: function(file){
    this.$Modal.info({
        title: '超出文件大小限制',
        content: '文件 ' + file.name + ' 太大,不能超过 2M。'
    })
},

# 校验文件个数
:before-upload="handleBeforeUpload"

handleBeforeUpload: function () {
    const check = this.uploadList.length < 1;
    if (!check) {
        this.$Modal.info({
            title: '温馨提示',
            content: '只能上传一个文件,如果需要重传,请删除当前文件'
        })
    }
    return check;
},

# 点击删除已经上传的某个图片
:on-remove="handleRemove"

handleRemove: function(file){
    const fileList = this.$refs.upload.fileList;
    this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
},

# 上传接口调用成功返回值
:on-success="handleSuccess"

handleSuccess: function(res){
    console.log(res)
}

# 初始化当前图片组件
mounted:function() {
    this.uploadList = this.$refs.upload.fileList;
},

# 定义图片组件的常量
data () {
    return {
        uploadList: []
    }
}

做一个有底线的博客主