antdesign的upload文档
大部分的项目中, 都会与后端接口进行配合, 此处就不使用action了
在接下来的例子, 会用到 beforeUpload/customRequest/change, 回调参数形式请自行查阅文档
// template
<a-form :form="form">
<a-form-item label="模板图片">
<a-upload
name="img"
:multiple="false"
:customRequest="(e)=>{actionLogoFunc(e, 'list_file', 'img')}"
@change="(e)=>{fileListChange(e, 'list_file', 'fileList')}"
:before-upload="(e)=>{beforeUpload(e, 'fileList')}"
v-decorator="['img', {rules: [{required: true, message: '请上传图片!'}]}]"
>
<div v-if="img" class="edit-img">
<span class="edit-icon">
<a-icon style="font-size: 26px; color: #fff" type="edit" />
<a-icon @click.stop="delImg('list_file', 'fileList', 'img')" style="font-size: 26px; color: #fff; margin-left: 10px;" type="delete" />
</span>
<img style="width:90px;height:90px" :src="img" alt="" srcset="">
</div>
<a-button v-else><a-icon type="upload" />上传</a-button>
</a-upload>
</a-form-item>
</a-form>
// js
data(){
return {
img: null,
list_file: null,
fileList: [],
}
}
methods: {
actionLogoFunc(e, t, k) {
const fd = new FormData()
fd.append('file', e.file)
// 这里引入你的api, headers一般都需要做设置: {'Content-Type': 'application/x-www-form-urlencoded'}
fileUpload(fd).then(res => {
if(res.code == 200){
this[t].status = 'success'
this[k] = res.data.img
}
})
},
fileListChange(e, t, k) {
this[t] = e.file;
let len = e.fileList.length;
// 对原来e的file里面的数据作操作
if(this[k].length == 0){
e.fileList.splice(0, 1)
this[t] = ''
}else{
if(len > 1){
e.fileList.splice(0, 1)
this[k].splice(0, 1)
}
if(len == 0){
this[t] = ''
}
}
},
beforeUpload(file, t){
this[t] = [...this[t], file];
const isJpgOrPng = file.type.includes('image')
if (!isJpgOrPng) {
this.$message.error('只能上传图片格式');
this[t].splice(0, 1)
}
if(file.size > 10*1024*1024) {
this.$message.error('图片大小超过10M');
return
}
return isJpgOrPng;
},
delImg(t, k, i){
this[t] = null
this[k] = []
this[i] = null
},
}
// css
.edit-img{
width: 90px;
height: 90px;
position: relative;
display: flex;
align-items: center;
img{
width: 90px;
max-height: 90px;
}
.edit-icon{
background: rgba(0,0,0,.2);
position: absolute;
width: 90px;
height: 90px;
text-align: center;
line-height: 90px;
}
}
/** .ant-upload-list这里不能写在scoped中, 会不生效 **/
.ant-upload-list{
display: none;
}
上传前后的upload样式
在其他的组件应该也大同小异, 可以作为参考
**
有能够优化的地方, 欢迎留言讨论
**