blob: 2fec19d5bfc3fcfb152825018d5bded526b96ad2 [file] [log] [blame]
guangchao.xu070005a2020-12-07 09:56:40 +08001<template>
2 <view class="u-upload" v-if="!disabled">
3 <view
4 v-if="showUploadList"
5 class="u-list-item u-preview-wrap"
6 v-for="(item, index) in lists"
7 :key="index"
8 :style="{
9 width: $u.addUnit(width),
10 height: $u.addUnit(height)
11 }"
12 >
13 <view
14 v-if="deletable"
15 class="u-delete-icon"
16 @tap.stop="deleteItem(index)"
17 :style="{
18 background: delBgColor
19 }"
20 >
21 <u-icon class="u-icon" :name="delIcon" size="20" :color="delColor"></u-icon>
22 </view>
23 <u-line-progress
24 v-if="showProgress && item.progress > 0 && !item.error"
25 :show-percent="false"
26 height="16"
27 class="u-progress"
28 :percent="item.progress"
29 ></u-line-progress>
30 <view @tap.stop="retry(index)" v-if="item.error" class="u-error-btn">点击重试</view>
31 <image @tap.stop="doPreviewImage(item.url || item.path, index)" class="u-preview-image" v-if="!item.isImage" :src="item.url || item.path" :mode="imageMode"></image>
32 </view>
33 <slot name="file" :file="lists"></slot>
34 <view style="display: inline-block;" @tap="selectFile" v-if="maxCount > lists.length">
35 <slot name="addBtn"></slot>
36 <view
37 v-if="!customBtn"
38 class="u-list-item u-add-wrap"
39 hover-class="u-add-wrap__hover"
40 hover-stay-time="150"
41 :style="{
42 width: $u.addUnit(width),
43 height: $u.addUnit(height)
44 }"
45 >
46 <u-icon name="plus" class="u-add-btn" size="40"></u-icon>
47 <view class="u-add-tips">{{ uploadText }}</view>
48 </view>
49 </view>
50 </view>
51</template>
52
53<script>
54/**
55 * upload 图片上传
56 * @description 该组件用于上传图片场景
57 * @tutorial https://www.uviewui.com/components/upload.html
58 * @property {String} action 服务器上传地址
59 * @property {String Number} max-count 最大选择图片的数量(默认99)
60 * @property {Boolean} custom-btn 如果需要自定义选择图片的按钮,设置为true(默认false)
61 * @property {Boolean} show-progress 是否显示进度条(默认true)
62 * @property {Boolean} disabled 是否启用(显示/移仓)组件(默认false)
63 * @property {String} image-mode 预览图片等显示模式,可选值为uni的image的mode属性值(默认aspectFill)
64 * @property {String} del-icon 右上角删除图标名称,只能为uView内置图标
65 * @property {String} del-bg-color 右上角关闭按钮的背景颜色
66 * @property {String | Number} index 在各个回调事件中的最后一个参数返回,用于区别是哪一个组件的事件
67 * @property {String} del-color 右上角关闭按钮图标的颜色
68 * @property {Object} header 上传携带的头信息,对象形式
69 * @property {Object} form-data 上传额外携带的参数
70 * @property {String} name 上传文件的字段名,供后端获取使用(默认file)
71 * @property {Array<String>} size-type original 原图,compressed 压缩图,默认二者都有(默认['original', 'compressed'])
72 * @property {Array<String>} source-type 选择图片的来源,album-从相册选图,camera-使用相机,默认二者都有(默认['album', 'camera'])
73 * @property {Boolean} preview-full-image 是否可以通过uni.previewImage预览已选择的图片(默认true)
74 * @property {Boolean} multiple 是否开启图片多选,部分安卓机型不支持(默认true)
75 * @property {Boolean} deletable 是否显示删除图片的按钮(默认true)
76 * @property {String Number} max-size 选择单个文件的最大大小,单位B(byte),默认不限制(默认Number.MAX_VALUE)
77 * @property {Array<Object>} file-list 默认显示的图片列表,数组元素为对象,必须提供url属性
78 * @property {Boolean} upload-text 选择图片按钮的提示文字(默认“选择图片”)
79 * @property {Boolean} auto-upload 选择完图片是否自动上传,见上方说明(默认true)
80 * @property {Boolean} show-tips 特殊情况下是否自动提示toast,见上方说明(默认true)
81 * @property {Boolean} show-upload-list 是否显示组件内部的图片预览(默认true)
82 * @event {Function} on-oversize 图片大小超出最大允许大小
83 * @event {Function} on-preview 全屏预览图片时触发
84 * @event {Function} on-remove 移除图片时触发
85 * @event {Function} on-success 图片上传成功时触发
86 * @event {Function} on-change 图片上传后,无论成功或者失败都会触发
87 * @event {Function} on-error 图片上传失败时触发
88 * @event {Function} on-progress 图片上传过程中的进度变化过程触发
89 * @event {Function} on-uploaded 所有图片上传完毕触发
90 * @event {Function} on-choose-complete 每次选择图片后触发,只是让外部可以得知每次选择后,内部的文件列表
91 * @example <u-upload :action="action" :file-list="fileList" ></u-upload>
92 */
93export default {
94 name: 'u-upload',
95 props: {
96 //是否显示组件自带的图片预览功能
97 showUploadList: {
98 type: Boolean,
99 default: true
100 },
101 // 后端地址
102 action: {
103 type: String,
104 default: ''
105 },
106 // 最大上传数量
107 maxCount: {
108 type: [String, Number],
109 default: 52
110 },
111 // 是否显示进度条
112 showProgress: {
113 type: Boolean,
114 default: true
115 },
116 // 是否启用
117 disabled: {
118 type: Boolean,
119 default: false
120 },
121 // 预览上传的图片时的裁剪模式,和image组件mode属性一致
122 imageMode: {
123 type: String,
124 default: 'aspectFill'
125 },
126 // 头部信息
127 header: {
128 type: Object,
129 default() {
130 return {};
131 }
132 },
133 // 额外携带的参数
134 formData: {
135 type: Object,
136 default() {
137 return {};
138 }
139 },
140 // 上传的文件字段名
141 name: {
142 type: String,
143 default: 'file'
144 },
145 // 所选的图片的尺寸, 可选值为original compressed
146 sizeType: {
147 type: Array,
148 default() {
149 return ['original', 'compressed'];
150 }
151 },
152 sourceType: {
153 type: Array,
154 default() {
155 return ['album', 'camera'];
156 }
157 },
158 // 是否在点击预览图后展示全屏图片预览
159 previewFullImage: {
160 type: Boolean,
161 default: true
162 },
163 // 是否开启图片多选,部分安卓机型不支持
164 multiple: {
165 type: Boolean,
166 default: true
167 },
168 // 是否展示删除按钮
169 deletable: {
170 type: Boolean,
171 default: true
172 },
173 // 文件大小限制,单位为byte
174 maxSize: {
175 type: [String, Number],
176 default: Number.MAX_VALUE
177 },
178 // 显示已上传的文件列表
179 fileList: {
180 type: Array,
181 default() {
182 return [];
183 }
184 },
185 // 上传区域的提示文字
186 uploadText: {
187 type: String,
188 default: '选择图片'
189 },
190 // 是否自动上传
191 autoUpload: {
192 type: Boolean,
193 default: true
194 },
195 // 是否显示toast消息提示
196 showTips: {
197 type: Boolean,
198 default: true
199 },
200 // 是否通过slot自定义传入选择图标的按钮
201 customBtn: {
202 type: Boolean,
203 default: false
204 },
205 // 内部预览图片区域和选择图片按钮的区域宽度
206 width: {
207 type: [String, Number],
208 default: 200
209 },
210 // 内部预览图片区域和选择图片按钮的区域高度
211 height: {
212 type: [String, Number],
213 default: 200
214 },
215 // 右上角关闭按钮的背景颜色
216 delBgColor: {
217 type: String,
218 default: '#fa3534'
219 },
220 // 右上角关闭按钮的叉号图标的颜色
221 delColor: {
222 type: String,
223 default: '#ffffff'
224 },
225 // 右上角删除图标名称,只能为uView内置图标
226 delIcon: {
227 type: String,
228 default: 'close'
229 },
230 // 如果上传后的返回值为json字符串,是否自动转json
231 toJson: {
232 type: Boolean,
233 default: true
234 },
235 // 上传前的钩子,每个文件上传前都会执行
236 beforeUpload: {
237 type: Function,
238 default: null
239 },
240 // 移除文件前的钩子
241 beforeRemove: {
242 type: Function,
243 default: null
244 },
245 // 允许上传的图片后缀
246 limitType:{
247 type: Array,
248 default() {
249 return ['png', 'jpg', 'jpeg', 'webp', 'gif'];
250 }
251 },
252 // 在各个回调事件中的最后一个参数返回,用于区别是哪一个组件的事件
253 index: {
254 type: [Number, String],
255 default: ''
256 }
257 },
258 mounted() {},
259 data() {
260 return {
261 lists: [],
262 isInCount: true,
263 uploading: false
264 };
265 },
266 watch: {
267 fileList: {
268 immediate: true,
269 handler(val) {
270 val.map(value => {
271 // 首先检查内部是否已经添加过这张图片,因为外部绑定了一个对象给fileList的话(对象引用),进行修改外部fileList
272 // 时,会触发watch,导致重新把原来的图片再次添加到this.lists
273 // 数组的some方法意思是,只要数组元素有任意一个元素条件符合,就返回true,而另一个数组的every方法的意思是数组所有元素都符合条件才返回true
274 let tmp = this.lists.some(val => {
275 return val.url == value.url;
276 })
277 // 如果内部没有这个图片(tmp为false),则添加到内部
278 !tmp && this.lists.push({ url: value.url, error: false, progress: 100 });
279 });
280 }
281 },
282 // 监听lists的变化,发出事件
283 lists(n) {
284 this.$emit('on-list-change', n, this.index);
285 }
286 },
287 methods: {
288 // 清除列表
289 clear() {
290 this.lists = [];
291 },
292 // 重新上传队列中上传失败的所有文件
293 reUpload() {
294 this.uploadFile();
295 },
296 // 选择图片
297 selectFile() {
298 if (this.disabled) return;
299 const { name = '', maxCount, multiple, maxSize, sizeType, lists, camera, compressed, maxDuration, sourceType } = this;
300 let chooseFile = null;
301 const newMaxCount = maxCount - lists.length;
302 // 设置为只选择图片的时候使用 chooseImage 来实现
303 chooseFile = new Promise((resolve, reject) => {
304 uni.chooseImage({
305 count: multiple ? (newMaxCount > 9 ? 9 : newMaxCount) : 1,
306 sourceType: sourceType,
307 sizeType,
308 success: resolve,
309 fail: reject
310 });
311 });
312 chooseFile
313 .then(res => {
314 let file = null;
315 let listOldLength = this.lists.length;
316 res.tempFiles.map((val, index) => {
317 // 检查文件后缀是否允许,如果不在this.limitType内,就会返回false
318 if(!this.checkFileExt(val)) return ;
319
320 // 如果是非多选,index大于等于1或者超出最大限制数量时,不处理
321 if (!multiple && index >= 1) return;
322 if (val.size > maxSize) {
323 this.$emit('on-oversize', val, this.lists, this.index);
324 this.showToast('超出允许的文件大小');
325 } else {
326 if (maxCount <= lists.length) {
327 this.$emit('on-exceed', val, this.lists, this.index);
328 this.showToast('超出最大允许的文件个数');
329 return;
330 }
331 lists.push({
332 url: val.path,
333 progress: 0,
334 error: false,
335 file: val
336 });
337 }
338 });
339 // 每次图片选择完,抛出一个事件,并将当前内部选择的图片数组抛出去
340 this.$emit('on-choose-complete', this.lists, this.index);
341 if (this.autoUpload) this.uploadFile(listOldLength);
342 })
343 .catch(error => {
344 this.$emit('on-choose-fail', error);
345 });
346 },
347 // 提示用户消息
348 showToast(message, force = false) {
349 if (this.showTips || force) {
350 uni.showToast({
351 title: message,
352 icon: 'none'
353 });
354 }
355 },
356 // 该方法供用户通过ref调用,手动上传
357 upload() {
358 this.uploadFile();
359 },
360 // 对失败的图片重新上传
361 retry(index) {
362 this.lists[index].progress = 0;
363 this.lists[index].error = false;
364 this.lists[index].response = null;
365 uni.showLoading({
366 title: '重新上传'
367 });
368 this.uploadFile(index);
369 },
370 // 上传图片
371 async uploadFile(index = 0) {
372 if (this.disabled) return;
373 if (this.uploading) return;
374 // 全部上传完成
375 if (index >= this.lists.length) {
376 this.$emit('on-uploaded', this.lists, this.index);
377 return;
378 }
379 // 检查是否是已上传或者正在上传中
380 if (this.lists[index].progress == 100) {
381 if (this.autoUpload == false) this.uploadFile(index + 1);
382 return;
383 }
384 // 执行before-upload钩子
385 if(this.beforeUpload && typeof(this.beforeUpload) === 'function') {
386 // 执行回调,同时传入索引和文件列表当作参数
387 // 在微信,支付宝等环境(H5正常),会导致父组件定义的customBack()函数体中的this变成子组件的this
388 // 通过bind()方法,绑定父组件的this,让this.customBack()的this为父组件的上下文
389 // 因为upload组件可能会被嵌套在其他组件内,比如u-form,这时this.$parent其实为u-form的this,
390 // 非页面的this,所以这里需要往上历遍,一直寻找到最顶端的$parent,这里用了this.$u.$parent.call(this)
391 // 明白意思即可,无需纠结this.$u.$parent.call(this)的细节
392 let beforeResponse = this.beforeUpload.bind(this.$u.$parent.call(this))(index, this.lists);
393 // 判断是否返回了promise
394 if (!!beforeResponse && typeof beforeResponse.then === 'function') {
395 await beforeResponse.then(res => {
396 // promise返回成功,不进行动作,继续上传
397 }).catch(err => {
398 // 进入catch回调的话,继续下一张
399 return this.uploadFile(index + 1);
400 })
401 } else if(beforeResponse === false) {
402 // 如果返回false,继续下一张图片的上传
403 return this.uploadFile(index + 1);
404 } else {
405 // 此处为返回"true"的情形,这里不写代码,就跳过此处,继续执行当前的上传逻辑
406 }
407 }
408 // 检查上传地址
409 if (!this.action) {
410 this.showToast('请配置上传地址', true);
411 return;
412 }
413 this.lists[index].error = false;
414 this.uploading = true;
415 // 创建上传对象
416 const task = uni.uploadFile({
417 url: this.action,
418 filePath: this.lists[index].url,
419 name: this.name,
420 formData: this.formData,
421 header: this.header,
422 success: res => {
423 // 判断是否json字符串,将其转为json格式
424 let data = this.toJson && this.$u.test.jsonString(res.data) ? JSON.parse(res.data) : res.data;
425 if (![200, 201, 204].includes(res.statusCode)) {
426 this.uploadError(index, data);
427 } else {
428 // 上传成功
429 this.lists[index].response = data;
430 this.lists[index].progress = 100;
431 this.lists[index].error = false;
432 this.$emit('on-success', data, index, this.lists, this.index);
433 }
434 },
435 fail: e => {
436 this.uploadError(index, e);
437 },
438 complete: res => {
439 uni.hideLoading();
440 this.uploading = false;
441 this.uploadFile(index + 1);
442 this.$emit('on-change', res, index, this.lists, this.index);
443 }
444 });
445 task.onProgressUpdate(res => {
446 if (res.progress > 0) {
447 this.lists[index].progress = res.progress;
448 this.$emit('on-progress', res, index, this.lists, this.index);
449 }
450 });
451 },
452 // 上传失败
453 uploadError(index, err) {
454 this.lists[index].progress = 0;
455 this.lists[index].error = true;
456 this.lists[index].response = null;
457 this.$emit('on-error', err, index, this.lists, this.index);
458 this.showToast('上传失败,请重试');
459 },
460 // 删除一个图片
461 deleteItem(index) {
462 uni.showModal({
463 title: '提示',
464 content: '您确定要删除此项吗?',
465 success: async (res) => {
466 if (res.confirm) {
467 // 先检查是否有定义before-remove移除前钩子
468 // 执行before-remove钩子
469 if(this.beforeRemove && typeof(this.beforeRemove) === 'function') {
470 // 此处钩子执行 原理同before-remove参数,见上方注释
471 let beforeResponse = this.beforeRemove.bind(this.$u.$parent.call(this))(index, this.lists);
472 // 判断是否返回了promise
473 if (!!beforeResponse && typeof beforeResponse.then === 'function') {
474 await beforeResponse.then(res => {
475 // promise返回成功,不进行动作,继续上传
476 this.handlerDeleteItem(index);
477 }).catch(err => {
478 // 如果进入promise的reject,终止删除操作
479 this.showToast('已终止移除');
480 })
481 } else if(beforeResponse === false) {
482 // 返回false,终止删除
483 this.showToast('已终止移除');
484 } else {
485 // 如果返回true,执行删除操作
486 this.handlerDeleteItem(index);
487 }
488 } else {
489 // 如果不存在before-remove钩子,
490 this.handlerDeleteItem(index);
491 }
492 }
493 }
494 });
495 },
496 // 执行移除图片的动作,上方代码只是判断是否可以移除
497 handlerDeleteItem(index) {
498 // 如果文件正在上传中,终止上传任务,进度在0 < progress < 100则意味着正在上传
499 if (this.lists[index].process < 100 && this.lists[index].process > 0) {
500 typeof this.lists[index].uploadTask != 'undefined' && this.lists[index].uploadTask.abort();
501 }
502 this.lists.splice(index, 1);
503 this.$forceUpdate();
504 this.$emit('on-remove', index, this.lists, this.index);
505 this.showToast('移除成功');
506 },
507 // 用户通过ref手动的形式,移除一张图片
508 remove(index) {
509 // 判断索引的合法范围
510 if (index >= 0 && index < this.lists.length) {
511 this.lists.splice(index, 1);
512 this.$emit('on-list-change', this.lists, this.index);
513 }
514 },
515 // 预览图片
516 doPreviewImage(url, index) {
517 if (!this.previewFullImage) return;
518 const images = this.lists.map(item => item.url || item.path);
519 uni.previewImage({
520 urls: images,
521 current: url,
522 success: () => {
523 this.$emit('on-preview', url, this.lists, this.index);
524 },
525 fail: () => {
526 uni.showToast({
527 title: '预览图片失败',
528 icon: 'none'
529 });
530 }
531 });
532 },
533 // 判断文件后缀是否允许
534 checkFileExt(file) {
535 // 检查是否在允许的后缀中
536 let noArrowExt = false;
537 // 获取后缀名
538 let fileExt = '';
539 const reg = /.+\./;
540 // 如果是H5,需要从name中判断
541 // #ifdef H5
542 fileExt = file.name.replace(reg, "").toLowerCase();
543 // #endif
544 // 非H5,需要从path中读取后缀
545 // #ifndef H5
546 fileExt = file.path.replace(reg, "").toLowerCase();
547 // #endif
548 // 使用数组的some方法,只要符合limitType中的一个,就返回true
549 noArrowExt = this.limitType.some(ext => {
550 // 转为小写
551 return ext.toLowerCase() === fileExt;
552 })
553 if(!noArrowExt) this.showToast(`不允许选择${fileExt}格式的文件`);
554 return noArrowExt;
555 }
556 }
557};
558</script>
559
560<style lang="scss" scoped>
561@import '../../libs/css/style.components.scss';
562
563.u-upload {
564 @include vue-flex;
565 flex-wrap: wrap;
566 align-items: center;
567}
568
569.u-list-item {
570 width: 200rpx;
571 height: 200rpx;
572 overflow: hidden;
573 margin: 10rpx;
574 background: rgb(244, 245, 246);
575 position: relative;
576 border-radius: 10rpx;
577 /* #ifndef APP-NVUE */
578 display: flex;
579 /* #endif */
580 align-items: center;
581 justify-content: center;
582}
583
584.u-preview-wrap {
585 border: 1px solid rgb(235, 236, 238);
586}
587
588.u-add-wrap {
589 flex-direction: column;
590 color: $u-content-color;
591 font-size: 26rpx;
592}
593
594.u-add-tips {
595 margin-top: 20rpx;
596 line-height: 40rpx;
597}
598
599.u-add-wrap__hover {
600 background-color: rgb(235, 236, 238);
601}
602
603.u-preview-image {
604 display: block;
605 width: 100%;
606 height: 100%;
607 border-radius: 10rpx;
608}
609
610.u-delete-icon {
611 position: absolute;
612 top: 10rpx;
613 right: 10rpx;
614 z-index: 10;
615 background-color: $u-type-error;
616 border-radius: 100rpx;
617 width: 44rpx;
618 height: 44rpx;
619 @include vue-flex;
620 align-items: center;
621 justify-content: center;
622}
623
624.u-icon {
625 @include vue-flex;
626 align-items: center;
627 justify-content: center;
628}
629
630.u-progress {
631 position: absolute;
632 bottom: 10rpx;
633 left: 8rpx;
634 right: 8rpx;
635 z-index: 9;
636 width: auto;
637}
638
639.u-error-btn {
640 color: #ffffff;
641 background-color: $u-type-error;
642 font-size: 20rpx;
643 padding: 4px 0;
644 text-align: center;
645 position: absolute;
646 bottom: 0;
647 left: 0;
648 right: 0;
649 z-index: 9;
650 line-height: 1;
651}
652</style>