效果图:
- 引入Upload组件;
<el-upload
class="centerImg"
:class="{hide:hideUploadIcon}"
:action="' '"//请求地址,手动上传写为空
list-type="picture-card"
:on-preview="handlePictureCardPreviewIcon"
:on-remove="handleRemoveIcon"
:auto-upload="false"//false,手动上传
:limit="1"//限制只能上传一张图片
:on-change="handleAvatarChangeIcon"//文件状态改变时的钩子,
ref="uploadicon"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-button @click="iconDialogVisible = false">取 消</el-button>
<el-button type="primary" @click="saveIco()" >提 交</el-button>
2.点击上传前,取到图片路径
handleAvatarChangeIcon(file,fileList){
const isJPG = file.raw.type === 'image/jpeg'
const isPNG = file.raw.type === 'image/png'
const isLt2M = file.raw.size / 1024 / 1024 < 0.5
this.hideUploadIcon = fileList.length >= 1;
if (!isPNG && !isJPG) {
this.$message.error('上传图片只能是 JPG/PNG 格式!')
return false
} else if (!isLt2M) {
this.$message.error('上传图片大小不能超过 200kb!')
return false
} else if (isLt2M && (isPNG || isJPG)) {
this.iconformData.img = file.raw;//图片的url
this.iconformData.name = file.name;//图片的名字
}
}
3.点击上传,设置headers,传参格式为formdata
saveIco(){
let config = {
timeout: 30000,
headers: {
"Content-Type": "multipart/form-data",//设置headers
token: getToken()
}
};
const formData = new FormData()
for (const key in this.iconformData) {
formData.append(key, this.iconformData[key]);//传参改为formData格式
}
axios
.post(
SERVER_BASE_URL + "/gateway/dealFile/dealIcoImg",//请求后端的url
formData,
config
)
.then(res => {
if(res.data.rtnCode==200){
//上传成功
}else{
//上传失败
}
})
.catch(error => {
//请求失败
});
}