u-upload.vue 17 KB

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