华为云媒资上传vue代码
时间: 2024-04-14 07:14:35 浏览: 103
<template>
<div class="upload">
<el-upload
class="upload-demo"
:action="uploadUrl"
:headers="headers"
:on-success="handleSuccess"
:before-upload="beforeUpload"
:on-error="handleError"
:auto-upload="false"
:show-file-list="false"
>
<el-button
type="primary"
size="medium"
:loading="loading"
:disabled="disabled"
icon="el-icon-upload"
>
{{ buttonText }}
</el-button>
<span class="upload-tip">{{ uploadTip }}</span>
</el-upload>
</div>
</template>
<script>
export default {
name: "Upload",
props: {
buttonText: {
type: String,
default: "上传"
},
uploadUrl: {
type: String,
required: true
},
uploadTip: {
type: String,
default: "支持文件类型:jpg、jpeg、png、gif、bmp,文件大小不超过 5MB"
},
headers: {
type: Object,
default() {
return {
Authorization: ""
};
}
}
},
data() {
return {
loading: false,
disabled: false
};
},
methods: {
beforeUpload(file) {
const isJPG = file.type === "image/jpeg";
const isPNG = file.type === "image/png";
const isGIF = file.type === "image/gif";
const isBMP = file.type === "image/bmp";
const isLt5M = file.size / 1024 / 1024 < 5;
if (!isJPG && !isPNG && !isGIF && !isBMP) {
this.$message.error("上传图片只能是 JPG/PNG/GIF/BMP 格式!");
return false;
}
if (!isLt5M) {
this.$message.error("上传图片大小不能超过 5MB!");
return false;
}
this.loading = true;
this.disabled = true;
return true;
},
handleSuccess(response, file) {
this.loading = false;
this.disabled = false;
if (response.code === 200) {
this.$emit("success", response.data);
} else {
this.$message.error(response.msg);
}
},
handleError(error, file) {
this.loading = false;
this.disabled = false;
this.$message.error("上传失败,请重试!");
}
}
};
</script>
<style scoped>
.upload {
display: inline-block;
vertical-align: middle;
}
.upload-tip {
display: inline-block;
font-size: 12px;
color: #c0c4cc;
margin-left: 10px;
vertical-align: middle;
}
</style>
阅读全文