admin
2024-11-12 a6316ee0ab82a0f3fc2691f8b5ddbd79e1567086
提交 | 用户 | 时间
a6316e 1 <template>
A 2   <div class="component-upload-image">
3     <el-upload
4       multiple
5       :action="uploadImgUrl"
6       list-type="picture-card"
7       :on-success="handleUploadSuccess"
8       :before-upload="handleBeforeUpload"
9       :limit="limit"
10       :on-error="handleUploadError"
11       :on-exceed="handleExceed"
12       ref="imageUpload"
13       :on-remove="handleDelete"
14       :show-file-list="true"
15       :headers="headers"
16       :file-list="fileList"
17       :on-preview="handlePictureCardPreview"
18       :class="{hide: this.fileList.length >= this.limit}"
19     >
20       <i class="el-icon-plus"></i>
21     </el-upload>
22
23     <!-- 上传提示 -->
24     <div class="el-upload__tip" slot="tip" v-if="showTip">
25       请上传
26       <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
27       <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
28       的文件
29     </div>
30
31     <el-dialog
32       :visible.sync="dialogVisible"
33       title="预览"
34       width="800"
35       append-to-body
36     >
37       <img
38         :src="dialogImageUrl"
39         style="display: block; max-width: 100%; margin: 0 auto"
40       />
41     </el-dialog>
42   </div>
43 </template>
44
45 <script>
46 import { getToken } from "@/utils/auth";
47 import { isExternal } from "@/utils/validate";
48
49 export default {
50   props: {
51     value: [String, Object, Array],
52     // 图片数量限制
53     limit: {
54       type: Number,
55       default: 5,
56     },
57     // 大小限制(MB)
58     fileSize: {
59        type: Number,
60       default: 5,
61     },
62     // 文件类型, 例如['png', 'jpg', 'jpeg']
63     fileType: {
64       type: Array,
65       default: () => ["png", "jpg", "jpeg"],
66     },
67     // 是否显示提示
68     isShowTip: {
69       type: Boolean,
70       default: true
71     }
72   },
73   data() {
74     return {
75       number: 0,
76       uploadList: [],
77       dialogImageUrl: "",
78       dialogVisible: false,
79       hideUpload: false,
80       baseUrl: process.env.VUE_APP_BASE_API,
81       uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
82       headers: {
83         Authorization: "Bearer " + getToken(),
84       },
85       fileList: []
86     };
87   },
88   watch: {
89     value: {
90       handler(val) {
91         if (val) {
92           // 首先将值转为数组
93           const list = Array.isArray(val) ? val : this.value.split(',');
94           // 然后将数组转为对象数组
95           this.fileList = list.map(item => {
96             if (typeof item === "string") {
97               if (item.indexOf(this.baseUrl) === -1 && !isExternal(item)) {
98                   item = { name: this.baseUrl + item, url: this.baseUrl + item };
99               } else {
100                   item = { name: item, url: item };
101               }
102             }
103             return item;
104           });
105         } else {
106           this.fileList = [];
107           return [];
108         }
109       },
110       deep: true,
111       immediate: true
112     }
113   },
114   computed: {
115     // 是否显示提示
116     showTip() {
117       return this.isShowTip && (this.fileType || this.fileSize);
118     },
119   },
120   methods: {
121     // 上传前loading加载
122     handleBeforeUpload(file) {
123       let isImg = false;
124       if (this.fileType.length) {
125         let fileExtension = "";
126         if (file.name.lastIndexOf(".") > -1) {
127           fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
128         }
129         isImg = this.fileType.some(type => {
130           if (file.type.indexOf(type) > -1) return true;
131           if (fileExtension && fileExtension.indexOf(type) > -1) return true;
132           return false;
133         });
134       } else {
135         isImg = file.type.indexOf("image") > -1;
136       }
137
138       if (!isImg) {
139         this.$modal.msgError(`文件格式不正确,请上传${this.fileType.join("/")}图片格式文件!`);
140         return false;
141       }
142       if (file.name.includes(',')) {
143         this.$modal.msgError('文件名不正确,不能包含英文逗号!');
144         return false;
145       }
146       if (this.fileSize) {
147         const isLt = file.size / 1024 / 1024 < this.fileSize;
148         if (!isLt) {
149           this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
150           return false;
151         }
152       }
153       this.$modal.loading("正在上传图片,请稍候...");
154       this.number++;
155     },
156     // 文件个数超出
157     handleExceed() {
158       this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
159     },
160     // 上传成功回调
161     handleUploadSuccess(res, file) {
162       if (res.code === 200) {
163         this.uploadList.push({ name: res.fileName, url: res.fileName });
164         this.uploadedSuccessfully();
165       } else {
166         this.number--;
167         this.$modal.closeLoading();
168         this.$modal.msgError(res.msg);
169         this.$refs.imageUpload.handleRemove(file);
170         this.uploadedSuccessfully();
171       }
172     },
173     // 删除图片
174     handleDelete(file) {
175       const findex = this.fileList.map(f => f.name).indexOf(file.name);
176       if (findex > -1) {
177         this.fileList.splice(findex, 1);
178         this.$emit("input", this.listToString(this.fileList));
179       }
180     },
181     // 上传失败
182     handleUploadError() {
183       this.$modal.msgError("上传图片失败,请重试");
184       this.$modal.closeLoading();
185     },
186     // 上传结束处理
187     uploadedSuccessfully() {
188       if (this.number > 0 && this.uploadList.length === this.number) {
189         this.fileList = this.fileList.concat(this.uploadList);
190         this.uploadList = [];
191         this.number = 0;
192         this.$emit("input", this.listToString(this.fileList));
193         this.$modal.closeLoading();
194       }
195     },
196     // 预览
197     handlePictureCardPreview(file) {
198       this.dialogImageUrl = file.url;
199       this.dialogVisible = true;
200     },
201     // 对象转成指定字符串分隔
202     listToString(list, separator) {
203       let strs = "";
204       separator = separator || ",";
205       for (let i in list) {
206         if (list[i].url) {
207           strs += list[i].url.replace(this.baseUrl, "") + separator;
208         }
209       }
210       return strs != '' ? strs.substr(0, strs.length - 1) : '';
211     }
212   }
213 };
214 </script>
215 <style scoped lang="scss">
216 // .el-upload--picture-card 控制加号部分
217 ::v-deep.hide .el-upload--picture-card {
218     display: none;
219 }
220 // 去掉动画效果
221 ::v-deep .el-list-enter-active,
222 ::v-deep .el-list-leave-active {
223     transition: all 0s;
224 }
225
226 ::v-deep .el-list-enter, .el-list-leave-active {
227   opacity: 0;
228   transform: translateY(0);
229 }
230 </style>
231