封装文件上传组件
<template>
<div class="upload-wrap">
<co-upload
:action="baseUrl + '/sys/pic/upload'"
:http-request="httpRequest"
ref="upload"
name="file"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:headers="myHeaders"
>
<img v-if="imgUrl" :src="imgUrl" class="avatar" />
<co-button v-else>点击上传</co-button>
</co-upload>
</div>
</template>
<script>
import { mapActions, mapState, mapMutations } from "vuex";
export default {
data() {
return {
baseUrl: "http://10.16.224.65:8090",
myHeaders: { "Content-Type": "multipart/form-data" },
imageUrl: "",
};
},
computed: {
...mapState("user", ["userName"]),
...mapState("directoryManagement", [
"firstLevelList",
"pageCurrent",
"pageSize",
"downLoading",
"total",
"menu",
"roleType",
"sencodLevelData",
"configurationPass",
"menuId",
"imgUrl",
]),
},
mounted() {
console.log("this.imgUrl;", this.imgUrl);
this.imageUrl = this.imgUrl;
},
methods: {
...mapActions("directoryManagement", ["getUpload", "updateStates"]),
handleAvatarSuccess(res) {},
//文件上传接口
httpRequest(param) {
let file = param.file; // 相当于input里取得的files
let formData = new FormData(); // FormData 对象
formData.append("pic", file); // 文件对象
this.getUpload(formData)
.then((res) => {
console.log("res文件上传", res);
if (res.code == 200) {
this.updateStates({
imgUrl: res.url,
});
// this.imageUrl = res.url;
this.$emit("imageUrl1", res.url);
} else {
this.$message.error("上传失败");
}
})
.catch((e) => {
this.$message.error("上传失败");
});
},
},
};
</script>
<style lang="scss" scoped>
.upload-wrap {
margin-left: 10px;
margin-right: 20px;
img {
width: 37px;
height: 37px;
border-radius: 50%;
}
}
</style>`在这里插入代码片`