vue-cli + ElementUI 实现自定义接口上传图片

4 篇文章 0 订阅

1、使用ElementUI风装好的方法

<el-upload class="upload-demo" 
:before-remove="beforeRemove" //移除前动作
:on-remove="handleRemove" //移除时动作
:action="action" //上传接口
:show-file-list="true"  //是否显示文件列表
:http-request='httprequest' //拦截上传动作
:before-upload="beforeupload" //选择完图片钩子
:file-list="fileList" //展示图片列表data
list-type="picture-card" multiple>
       <el-button size="small" type="primary">点击上传</el-button>
</el-upload> 

参数解释再ElementUI官网

2、在data里定义需要用到的参数(可能有遗漏)

imageUrl:'',
action:'', //上传接口 例子中接口需要封装formdata上传
fileList: [],
imgname:'',
delfileuid:'',

3、在methods中定义方法

//点击移除图片时
beforeRemove(file, fileList) {
    this.delfileuid = file.uid;
    console.log(file.uid);
    return this.$confirm(`确定移除 ${ file.name }?`);
},
//移除图片动作
handleRemove(file, fileList) {
    var that=this; 
        console.log(that.delfileuid)
    for(let i=0;i<that.fileList.length;i++)
    {
        if(that.fileList[i].uid == that.delfileuid){
            that.fileList.splice(i,1)
            console.log(that.fileList)
        }
    }
},


//阻止upload的自己上传,进行再操作
beforeupload(file) { 
    this.imgname =  file.name;
    const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
    this.$message.error('上传图片大小不能超过 2MB!');
    }
    else{
        console.log(file);
        //创建临时的路径来展示图片
        // var windowURL = window.URL || window.webkitURL; 
        // this.imageUrl=windowURL.createObjectURL(file);
        this.param = new FormData();
        this.param.append('imgFile', file, file.imgFile);
        var names = this.form.imgFile;
        //下面append的东西就会到form表单数据的fields中;
        this.param.append('message', names);
    }
    return isLt2M;
},
httprequest() {
    var that=this;
    let config = {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }; 
    this.$axios.post(this.action, this.param, config).then(function(res) { 
        if(res.data.invokeResultCode == 200){ //本项目中判断接口返回code
                that.$message.success("上传成功");
                that.imageUrl=res.data.data.url;
                that.fileList.push({name: that.imgname, url:res.data.data.url }) 
            }
            else{
                this.$message.error(res.data.invokeResultMessage);
            }
        }).catch((res) => { 
            this.$message.error('请稍候重试或联系管理员');
    })
},


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值