u-upload.vue 18 KB

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