upload_small.vue 17 KB

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