upload_small.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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. import uploadImage from '@/components/ossutil/uploadFile.js';
  92. export default {
  93. name: '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. delBgColor: {
  211. type: String,
  212. default: '#fa3534'
  213. },
  214. // 右上角关闭按钮的叉号图标的颜色
  215. delColor: {
  216. type: String,
  217. default: '#ffffff'
  218. },
  219. // 右上角删除图标名称,只能为uView内置图标
  220. delIcon: {
  221. type: String,
  222. default: 'close'
  223. },
  224. // 如果上传后的返回值为json字符串,是否自动转json
  225. toJson: {
  226. type: Boolean,
  227. default: true
  228. },
  229. // 上传前的钩子,每个文件上传前都会执行
  230. beforeUpload: {
  231. type: Function,
  232. default: null
  233. }
  234. },
  235. mounted() {},
  236. data() {
  237. return {
  238. lists: [],
  239. isInCount: true,
  240. uploading: false
  241. };
  242. },
  243. watch: {
  244. fileList: {
  245. immediate: true,
  246. handler(val) {
  247. val.map(value => {
  248. this.lists.push({ url: value.url, error: false, progress: 100 });
  249. });
  250. }
  251. }
  252. },
  253. methods: {
  254. // 清除列表
  255. clear() {
  256. this.lists = [];
  257. // 如果是清空形式的话,发出"on-list-change"事件
  258. this.$emit('on-list-change', this.lists);
  259. },
  260. // 重新上传队列中上传失败的所有文件
  261. reUpload() {
  262. this.uploadFile();
  263. },
  264. // 选择图片
  265. selectFile() {
  266. if (this.disabled) return;
  267. const { name = '', maxCount, multiple, maxSize, sizeType, lists, camera, compressed, maxDuration, sourceType } = this;
  268. let chooseFile = null;
  269. const newMaxCount = maxCount - lists.length;
  270. // 设置为只选择图片的时候使用 chooseImage 来实现
  271. chooseFile = new Promise((resolve, reject) => {
  272. uni.chooseImage({
  273. count: multiple ? (newMaxCount > 9 ? 9 : newMaxCount) : 1,
  274. sourceType: sourceType,
  275. sizeType,
  276. success: resolve,
  277. fail: reject
  278. });
  279. });
  280. chooseFile
  281. .then(res => {
  282. let file = null;
  283. let listOldLength = this.lists.length;
  284. res.tempFiles.map((val, index) => {
  285. // 如果是非多选,index大于等于1或者超出最大限制数量时,不处理
  286. if (!multiple && index >= 1) return;
  287. if (val.size > maxSize) {
  288. this.$emit('on-oversize', val, this.lists);
  289. this.showToast('超出允许的文件大小');
  290. } else {
  291. if (maxCount <= lists.length) {
  292. this.$emit('on-exceed', val, this.lists);
  293. this.showToast('超出最大允许的文件个数');
  294. return;
  295. }
  296. let fileName = '';
  297. let fileNameLength='';
  298. let fileFormat = '';
  299. //#ifdef H5
  300. fileName = val.name.lastIndexOf(".");
  301. fileNameLength = val.name.length;
  302. fileFormat = val.name.substring(fileName + 1, fileNameLength).toLowerCase();
  303. //#endif
  304. //#ifndef H5
  305. fileName = val.path.lastIndexOf(".");
  306. fileNameLength = val.path.length;
  307. fileFormat = val.path.substring(fileName + 1, fileNameLength).toLowerCase();
  308. //#endif
  309. lists.push({
  310. url: val.path,
  311. fileType: fileFormat,
  312. progress: 0,
  313. error: false
  314. });
  315. // 列表发生改变,发出事件,第二个参数为当前发生变化的项的索引
  316. this.$emit('on-list-change', this.lists);
  317. }
  318. });
  319. // 每次图片选择完,抛出一个事件,并将当前内部选择的图片数组抛出去
  320. this.$emit('on-choose-complete', this.lists);
  321. if (this.autoUpload) this.uploadFile(listOldLength);
  322. })
  323. .catch(error => {
  324. // this.$emit('on-error', error);
  325. });
  326. },
  327. // 提示用户消息
  328. showToast(message, force = false) {
  329. if (this.showTips || force) {
  330. uni.showToast({
  331. title: message,
  332. icon: 'none'
  333. });
  334. }
  335. },
  336. // 该方法供用户通过ref调用,手动上传
  337. upload() {
  338. this.uploadFile();
  339. },
  340. // 对失败的图片重新上传
  341. retry(index) {
  342. this.lists[index].progress = 0;
  343. this.lists[index].error = false;
  344. this.lists[index].response = null;
  345. uni.showLoading({
  346. title: '重新上传'
  347. });
  348. this.uploadFile(index);
  349. },
  350. // 上传图片
  351. async uploadFile(index = 0) {
  352. if (this.disabled) return;
  353. if (this.uploading) return;
  354. // 全部上传完成
  355. if (index >= this.lists.length) {
  356. this.$emit('on-uploaded', this.lists);
  357. return;
  358. }
  359. // 检查上传地址
  360. if (!this.action) {
  361. this.showToast('请配置上传地址', true);
  362. return;
  363. }
  364. // 检查是否是已上传或者正在上传中
  365. if (this.lists[index].progress == 100) {
  366. if (this.autoUpload == false) this.uploadFile(index + 1);
  367. return;
  368. }
  369. // 执行before-upload钩子
  370. if(this.beforeUpload && typeof(this.beforeUpload) === 'function') {
  371. // 执行回调,同时传入索引和文件列表当作参数
  372. let beforeResponse = this.beforeUpload(index, this.lists);
  373. // 判断是否返回了promise
  374. if (!!beforeResponse && typeof beforeResponse.then === 'function') {
  375. await beforeResponse.then(res => {
  376. // promise返回成功,不进行动作,继续上传
  377. }).catch(err => {
  378. // 进入catch回调的话,继续下一张
  379. return this.uploadFile(index + 1);
  380. })
  381. } else if(beforeResponse === false) {
  382. // 如果返回false,继续下一张图片的上传
  383. return this.uploadFile(index + 1);
  384. }
  385. }
  386. this.lists[index].error = false;
  387. this.uploading = true;
  388. uploadImage(this.lists[index].url, 'appData/',
  389. result => {
  390. // 上传成功
  391. this.lists[index].response = result;
  392. this.lists[index].progress = 0;
  393. this.lists[index].error = false;
  394. this.$emit('on-success', result, index, this.lists);
  395. }
  396. )
  397. // // 创建上传对象
  398. // const task = uni.uploadFile({
  399. // url: this.action,
  400. // filePath: this.lists[index].url,
  401. // name: this.name,
  402. // formData: this.formData,
  403. // header: this.header,
  404. // success: res => {
  405. // // 判断是否json字符串,将其转为json格式
  406. // let data = this.toJson && this.checkIsJSON(res.data) ? JSON.parse(res.data) : res.data;
  407. // if (![200, 201].includes(res.statusCode)) {
  408. // this.uploadError(index, data);
  409. // } else {
  410. // // 上传成功
  411. // this.lists[index].response = data;
  412. // this.lists[index].progress = 0;
  413. // this.lists[index].error = false;
  414. // this.$emit('on-success', data, index, this.lists);
  415. // }
  416. // },
  417. // fail: e => {
  418. // this.uploadError(index, e);
  419. // },
  420. // complete: res => {
  421. // uni.hideLoading();
  422. // this.uploading = false;
  423. // this.uploadFile(index + 1);
  424. // this.$emit('on-change', res, index, this.lists);
  425. // }
  426. // });
  427. // task.onProgressUpdate(res => {
  428. // if (res.progress > 0) {
  429. // this.lists[index].progress = res.progress;
  430. // this.$emit('on-progress', res, index, this.lists);
  431. // }
  432. // });
  433. },
  434. // 上传失败
  435. uploadError(index, err) {
  436. this.lists[index].progress = 0;
  437. this.lists[index].error = true;
  438. this.lists[index].response = null;
  439. this.$emit('on-error', err, index, this.lists);
  440. this.showToast('上传失败,请重试');
  441. },
  442. // 删除一个图片
  443. deleteItem(index) {
  444. uni.showModal({
  445. title: '提示',
  446. content: '您确定要删除此项吗?',
  447. success: res => {
  448. if (res.confirm) {
  449. if (this.lists[index].process < 100 && this.lists[index].process > 0) {
  450. typeof this.lists[index].uploadTask != 'undefined' && this.lists[index].uploadTask.abort();
  451. }
  452. this.lists.splice(index, 1);
  453. this.$forceUpdate();
  454. this.$emit('on-remove', index, this.lists);
  455. this.showToast('移除成功');
  456. // 列表发生改变,发出事件
  457. this.$emit('on-list-change', this.lists);
  458. }
  459. }
  460. });
  461. },
  462. // 用户通过ref手动的形式,移除一张图片
  463. remove(index) {
  464. // 判断索引的合法范围
  465. if (index >= 0 && index < this.lists.length) {
  466. this.lists.splice(index, 1);
  467. this.$emit('on-list-change', this.lists);
  468. }
  469. },
  470. // 预览图片
  471. doPreviewImage(url, index) {
  472. if (!this.previewFullImage) return;
  473. const images = this.lists.map(item => item.url || item.path);
  474. uni.previewImage({
  475. urls: images,
  476. current: url,
  477. success: () => {
  478. this.$emit('on-preview', url, this.lists);
  479. },
  480. fail: () => {
  481. uni.showToast({
  482. title: '预览图片失败',
  483. icon: 'none'
  484. });
  485. }
  486. });
  487. },
  488. // 判断是否json字符串
  489. checkIsJSON(str) {
  490. if (typeof str == 'string') {
  491. try {
  492. var obj = JSON.parse(str);
  493. if (typeof obj == 'object' && obj) {
  494. return true;
  495. } else {
  496. return false;
  497. }
  498. } catch (e) {
  499. return false;
  500. }
  501. }
  502. return false;
  503. }
  504. }
  505. };
  506. </script>
  507. <style lang="scss" scoped>
  508. // nvue不能用标签命名样式
  509. /* #ifndef APP-NVUE */
  510. image {
  511. display: inline-block;
  512. // 解决图片加载时可能会瞬间变形的问题
  513. will-change: transform;
  514. }
  515. view,
  516. text {
  517. box-sizing: border-box;
  518. flex-direction: row;
  519. }
  520. /* #endif */
  521. .u-upload {
  522. display: flex;
  523. flex-wrap: wrap;
  524. align-items: center;
  525. }
  526. .u-list-item {
  527. width: 200rpx;
  528. height: 200rpx;
  529. overflow: hidden;
  530. margin: 10rpx;
  531. background: rgb(244, 245, 246);
  532. position: relative;
  533. border-radius: 10rpx;
  534. display: inline-flex;
  535. align-items: center;
  536. justify-content: center;
  537. }
  538. .u-preview-wrap {
  539. border: 1px solid rgb(235, 236, 238);
  540. }
  541. .u-add-wrap {
  542. flex-direction: column;
  543. color: $u-content-color;
  544. font-size: 28rpx;
  545. }
  546. .u-add-tips {
  547. margin-top: 20rpx;
  548. }
  549. .u-add-wrap__hover {
  550. background-color: rgb(235, 236, 238);
  551. }
  552. .u-preview-image {
  553. display: block;
  554. width: 100%;
  555. height: 100%;
  556. border-radius: 10rpx;
  557. }
  558. .u-delete-icon {
  559. position: absolute;
  560. top: 10rpx;
  561. right: 10rpx;
  562. z-index: 10;
  563. background-color: $u-type-error;
  564. border-radius: 100rpx;
  565. width: 44rpx;
  566. height: 44rpx;
  567. display: flex;
  568. align-items: center;
  569. justify-content: center;
  570. }
  571. .u-icon {
  572. display: flex;
  573. align-items: center;
  574. justify-content: center;
  575. }
  576. .u-progress {
  577. position: absolute;
  578. bottom: 10rpx;
  579. left: 8rpx;
  580. right: 8rpx;
  581. z-index: 9;
  582. width: auto;
  583. }
  584. .u-error-btn {
  585. color: #ffffff;
  586. background-color: $u-type-error;
  587. font-size: 20rpx;
  588. padding: 4px 0;
  589. text-align: center;
  590. position: absolute;
  591. bottom: 0;
  592. left: 0;
  593. right: 0;
  594. z-index: 9;
  595. line-height: 1;
  596. }
  597. </style>