1、前端API:
export const commonUpload=obj=>{
return request({
url:`/api/common/upload`,
method:'post',
data:obj
})
}
2、前端页面:
<template>
<el-form>
....
<el-form-item label="照片">
<el-upload ref="upload" :file-list="fileList" :class="{hide:photoHide}"
:on-change="handleChange" :on-remove="photoRemove" list-type="picture-card"
action="#" :auto-upload="false"
>
<i class="el-icon-plus"></i>
</el-upload>
</el-form-item>
....
</el-form>
</template>
<script>
import {commonUpLoad} from '@/api/common'
export default{
data(){
return{
photoHide:false,
picUrl:'',
fileList:[],
}
},
methods:{
init(item){//初始化,获取数据
if(item.pic){
this.fileList.push({url:item.pic.picUrl})
this.pohotHide=true
}
},
cancleBtn(){//取消按钮
this.$refs.upload.clearFiles()
this.picUrl=''
this.fileList=[]
this.pohotHide=false
},
submitBtn(){//提交按钮
let param={...this.detailForm}
param.pic={picUrl:this.picUrl}
Object.keys(param).map(item=>{
if(Object.prototype.toString.call(param[item])==='[object Array]'){
param[item]=param[item].join(',')
}
})
getSave(param).then(res=>{//保存接口
//this.$parent.getData() //调用父级方法,更新数据
if(res.data.code==0){
this.$message.success('保存成功')
//this.cancelBtn() //重置
}
})
},
handleChange(file,fileList){//图片上传
let formData=new FormData()
formData.append('file',file.raw)
commonUpLoad(formData).then(res=>{
this.picUrl=res.data.url
this.detailForm.picId=res.data.pic_id
})
this.photoHide=fileList.length>=1;
},
photoRemove(file,fileList){//图片移除
this.photoHide=fileList.length>=1;
this.picUrl=''
}
}
}
</script>