您的位置:首页 > Web前端 > Vue.js

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

2018-12-13 15:37 1276 查看

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('请稍候重试或联系管理员');
})
},
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: