123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- <template>
- <div class="upload">
- <el-upload class="avatar-uploader"
- style="line-height: 0;display: inline-block"
- action="/api-web/uploadFile"
- :headers="headers"
- :show-file-list="false"
- v-loading="uploadImgLoading"
- accept=".jpg, .jpeg, .png"
- :on-success="handleImgSuccess"
- :on-error="handleUploadImgError"
- :before-upload="beforeImgUpload">
- <img v-if="imgUrl"
- :src="imgUrl"
- class="avatar" />
- <i v-else class="el-icon-plus avatar-uploader-icon"></i>
- </el-upload>
- </div>
- </template>
- <script>
- import load from "@/utils/loading";
- import { getToken } from "@/utils/auth";
- export default {
- data() {
- return {
- headers: {
- Authorization: getToken()
- },
- uploadImgLoading: false,
- imgUrl: null,
- };
- },
- props: {
- value: {
- // 组件状态
- type: String,
- },
- imageSizeM: { // 默认2M
- type: Number,
- default() {
- return 2
- }
- },
- imageType: { // 检测类型
- type: Object,
- default() {
- return {
- "image/png": true,
- "image/jpeg": true,
- "image/jpg": true,
- }
- }
- }
- },
- mounted() {},
- methods: {
- beforeImgUpload (file) {
- const isImage = this.imageType[file.type];
- const isLt2M = file.size / 1024 / 1024 < this.imageSizeM;
- console.log(isImage, isLt2M)
- if (!isImage) {
- this.$message.error("只能上传图片格式!");
- }
- if (!isLt2M) {
- this.$message.error("上传图片大小不能超过 2MB!");
- }
- if (isImage && isLt2M) {
- this.uploadImgLoading = true
- }
- return isImage && isLt2M;
- },
- handleUploadImgError (file) {
- this.uploadImgLoading = false
- this.$message.error('上传失败')
- },
- handleImgSuccess (res, file) {
- this.uploadImgLoading = false
- this.imgUrl = res.data.url
- },
- },
- watch: {
- value(newValue) {
- console.log(newValue);
- this.imgUrl = newValue
- },
- },
- beforeDestroy() {
- },
- };
- </script>
- <style lang="scss">
- /deep/.avatar-uploader .el-upload,
- /deep/.upload-demo .el-upload {
- border-radius: 6px;
- cursor: pointer;
- position: relative;
- overflow: hidden;
- }
- .avatar-uploader .el-upload:hover {
- border-color: #409eff;
- }
- .avatar-uploader-icon {
- border: 1px dashed #d9d9d9;
- font-size: 28px;
- color: #8c939d;
- width: 120px;
- height: 120px;
- line-height: 120px;
- text-align: center;
- }
- .avatar {
- width: 120px;
- height: 120px;
- display: block;
- }
- .ivu-upload {
- display: none;
- }
- </style>
|