本文已参与「新人创作礼」活动,一起开启掘金创作之路。
记录一次 vue+element-ui+qiniu 实现的图片上传。
图片参考如下:
代码片段如下:
// form表单
<el-form
:model="TeacherAddForm"
:rules="rules"
ref="TeacherAddForm"
label-width="100px"
class="demo-TeacherAddForm"
>
// form表单item
<el-form-item label="头像" prop="logo_url" required>
// 添加图片区域
<el-upload
class="avatar-uploader"
accept="image/jpeg,image/gif,image/png,image/bmp"
action="http://upload.qiniup.com/"
:show-file-list="false"
:data="uploadData"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<div
v-if="!TeacherAddForm.logo_url"
slot="tip"
class="el-upload__tip"
>
上传jpg/png文件,且不超过5M
</div>
// 用于展示图片
<img
v-if="TeacherAddForm.logo_url"
:src="TeacherAddForm.logo_url"
class="avatar"
/>
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
...
data() {
return {
uploadData: { token: "" },
imgHost: "",
TeacherAddForm: {
logo_url: ""
}
};
},
mounted() {
http.get("/public/qiniu/upload/token?bucket=imgs").then(res => {
this.uploadData.token = res.token;
this.imgHost = res.img_host; // 在七牛云自定义的图片下载域名
});
},
methods: {
// 图片文件上传成功时触发
handleAvatarSuccess(res, file) {
// res: {"key":"FjBCDRqa-yvLYDNYElaa9ENaWc4X", "hash": "xxx"}
this.TeacherAddForm.logo_url = this.imgHost + res.key; // 文件上传成功,则让页面显示对应图片
},
// 图片文件上传之前触发
beforeAvatarUpload(file) {
const isJpgPng = file.type === "image/jpeg" || file.type === "image/png"; // 判断文件是不是指定的图片类型
const isLt5M = file.size / 1024 / 1024 < 5; // 判断图片文件大小是否超过5M
if (!isJpgPng) {
this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
}
if (!isLt5M) {
this.$message.error("上传头像图片大小不能超过 5MB!");
}
return isJpgPng && isLt5M;
}
}
...
<style lang="scss" scoped>
.avatar-uploader /deep/ .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader /deep/ .el-upload:hover {
border-color: #409eff;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
“我们都是这个世界上的迷路者,我们都是按照自己认定的道路寻找方向,也许我们是对的,也许我们错了,或者有时候对了,有时候错了。在中国人所说的盖棺论定之前,在古罗马人所说的出生之前和死去之前,我们谁也不知道在前面的时间里等待我们的是什么。”