upload_small.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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: Number,
  89. default: 9
  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. console.log(1)
  279. if (maxCount <= lists.length) {
  280. this.$emit('on-exceed', val, this.lists);
  281. this.showToast('超出最大允许的文件个数');
  282. return;
  283. }
  284. let fileName = '';
  285. let fileNameLength = '';
  286. let fileFormat = '';
  287. //#ifdef H5
  288. fileName = val.name.lastIndexOf(".");
  289. fileNameLength = val.name.length;
  290. fileFormat = val.name.substring(fileName + 1, fileNameLength).toLowerCase();
  291. //#endif
  292. //#ifndef H5
  293. fileName = val.path.lastIndexOf(".");
  294. fileNameLength = val.path.length;
  295. fileFormat = val.path.substring(fileName + 1, fileNameLength).toLowerCase();
  296. //#endif
  297. lists.push({
  298. url: val.path,
  299. fileType: fileFormat,
  300. progress: 0,
  301. error: false
  302. });
  303. // 列表发生改变,发出事件,第二个参数为当前发生变化的项的索引
  304. this.$emit('on-list-change', this.lists);
  305. }
  306. });
  307. // 每次图片选择完,抛出一个事件,并将当前内部选择的图片数组抛出去
  308. this.$emit('on-choose-complete', this.lists);
  309. if (this.autoUpload) this.uploadFile(listOldLength);
  310. })
  311. .catch(error => {
  312. // this.$emit('on-error', error);
  313. });
  314. },
  315. // 提示用户消息
  316. showToast(message, force = false) {
  317. if (this.showTips || force) {
  318. uni.showToast({
  319. title: message,
  320. icon: 'none'
  321. });
  322. }
  323. },
  324. // 该方法供用户通过ref调用,手动上传
  325. upload() {
  326. this.uploadFile();
  327. },
  328. // 对失败的图片重新上传
  329. retry(index) {
  330. this.lists[index].progress = 0;
  331. this.lists[index].error = false;
  332. this.lists[index].response = null;
  333. uni.showLoading({
  334. title: '重新上传'
  335. });
  336. this.uploadFile(index);
  337. },
  338. // 上传图片
  339. async uploadFile(index = 0) {
  340. console.log(2)
  341. console.log("index", index)
  342. console.log("this.disabled", this.disabled)
  343. console.log("uploading", this.uploading)
  344. if (this.disabled) return;
  345. if (this.uploading) return;
  346. // 全部上传完成
  347. console.log("this.lists.length", this.lists.length)
  348. if (index >= this.lists.length) {
  349. this.$emit('on-uploaded', this.lists);
  350. return;
  351. }
  352. // 检查上传地址
  353. if (!this.action) {
  354. this.showToast('请配置上传地址', true);
  355. return;
  356. }
  357. // 检查是否是已上传或者正在上传中
  358. if (this.lists[index].progress == 100) {
  359. if (this.autoUpload == false) this.uploadFile(index + 1);
  360. return;
  361. }
  362. // 执行before-upload钩子
  363. if (this.beforeUpload && typeof(this.beforeUpload) === 'function') {
  364. // 执行回调,同时传入索引和文件列表当作参数
  365. let beforeResponse = this.beforeUpload(index, this.lists);
  366. // 判断是否返回了promise
  367. if (!!beforeResponse && typeof beforeResponse.then === 'function') {
  368. await beforeResponse.then(res => {
  369. // promise返回成功,不进行动作,继续上传
  370. }).catch(err => {
  371. // 进入catch回调的话,继续下一张
  372. return this.uploadFile(index + 1);
  373. })
  374. } else if (beforeResponse === false) {
  375. // 如果返回false,继续下一张图片的上传
  376. return this.uploadFile(index + 1);
  377. }
  378. }
  379. this.lists[index].error = false;
  380. // this.uploading = true;
  381. console.log(3)
  382. uploadImage(this.lists[index].url, 'appData/',
  383. result => {
  384. // 上传成功
  385. this.lists[index].response = result;
  386. this.lists[index].progress = 0;
  387. this.lists[index].error = false;
  388. this.$emit('on-success', result, index, this.lists);
  389. }
  390. )
  391. // // 创建上传对象
  392. // const task = uni.uploadFile({
  393. // url: this.action,
  394. // filePath: this.lists[index].url,
  395. // name: this.name,
  396. // formData: this.formData,
  397. // header: this.header,
  398. // success: res => {
  399. // // 判断是否json字符串,将其转为json格式
  400. // let data = this.toJson && this.checkIsJSON(res.data) ? JSON.parse(res.data) : res.data;
  401. // if (![200, 201].includes(res.statusCode)) {
  402. // this.uploadError(index, data);
  403. // } else {
  404. // // 上传成功
  405. // this.lists[index].response = data;
  406. // this.lists[index].progress = 0;
  407. // this.lists[index].error = false;
  408. // this.$emit('on-success', data, index, this.lists);
  409. // }
  410. // },
  411. // fail: e => {
  412. // this.uploadError(index, e);
  413. // },
  414. // complete: res => {
  415. // uni.hideLoading();
  416. // this.uploading = false;
  417. // this.uploadFile(index + 1);
  418. // this.$emit('on-change', res, index, this.lists);
  419. // }
  420. // });
  421. // task.onProgressUpdate(res => {
  422. // if (res.progress > 0) {
  423. // this.lists[index].progress = res.progress;
  424. // this.$emit('on-progress', res, index, this.lists);
  425. // }
  426. // });
  427. },
  428. // 上传失败
  429. uploadError(index, err) {
  430. this.lists[index].progress = 0;
  431. this.lists[index].error = true;
  432. this.lists[index].response = null;
  433. this.$emit('on-error', err, index, this.lists);
  434. this.showToast('上传失败,请重试');
  435. },
  436. // 删除一个图片
  437. deleteItem(index) {
  438. uni.showModal({
  439. title: '提示',
  440. content: '您确定要删除此项吗?',
  441. success: res => {
  442. if (res.confirm) {
  443. if (this.lists[index].process < 100 && this.lists[index].process > 0) {
  444. typeof this.lists[index].uploadTask != 'undefined' && this.lists[index]
  445. .uploadTask.abort();
  446. }
  447. this.lists.splice(index, 1);
  448. this.$forceUpdate();
  449. this.$emit('on-remove', index, this.lists);
  450. this.showToast('移除成功');
  451. // 列表发生改变,发出事件
  452. this.$emit('on-list-change', this.lists);
  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. // 判断是否json字符串
  484. checkIsJSON(str) {
  485. if (typeof str == 'string') {
  486. try {
  487. var obj = JSON.parse(str);
  488. if (typeof obj == 'object' && obj) {
  489. return true;
  490. } else {
  491. return false;
  492. }
  493. } catch (e) {
  494. return false;
  495. }
  496. }
  497. return false;
  498. }
  499. }
  500. };
  501. </script>
  502. <style lang="scss" scoped>
  503. // nvue不能用标签命名样式
  504. /* #ifndef APP-NVUE */
  505. image {
  506. display: inline-block;
  507. // 解决图片加载时可能会瞬间变形的问题
  508. will-change: transform;
  509. }
  510. view,
  511. text {
  512. box-sizing: border-box;
  513. flex-direction: row;
  514. }
  515. /* #endif */
  516. .u-upload {
  517. display: flex;
  518. flex-wrap: wrap;
  519. align-items: center;
  520. }
  521. .u-list-item {
  522. width: 200rpx;
  523. height: 200rpx;
  524. overflow: hidden;
  525. margin: 10rpx;
  526. background: #F5F6FA;
  527. position: relative;
  528. border-radius: 10rpx;
  529. display: inline-flex;
  530. align-items: center;
  531. justify-content: center;
  532. }
  533. .u-preview-wrap {
  534. border: 1px solid rgb(235, 236, 238);
  535. }
  536. .u-add-wrap {
  537. flex-direction: column;
  538. color: $u-content-color;
  539. font-size: 28rpx;
  540. }
  541. .u-add-tips {
  542. margin-top: 20rpx;
  543. }
  544. .u-add-wrap__hover {
  545. background-color: rgb(235, 236, 238);
  546. }
  547. .u-preview-image {
  548. display: block;
  549. width: 100%;
  550. height: 100%;
  551. border-radius: 10rpx;
  552. }
  553. .u-delete-icon {
  554. position: absolute;
  555. top: 10rpx;
  556. right: 10rpx;
  557. z-index: 10;
  558. background-color: $u-type-error;
  559. border-radius: 100rpx;
  560. width: 44rpx;
  561. height: 44rpx;
  562. display: flex;
  563. align-items: center;
  564. justify-content: center;
  565. }
  566. .u-icon {
  567. display: flex;
  568. align-items: center;
  569. justify-content: center;
  570. }
  571. .u-progress {
  572. position: absolute;
  573. bottom: 10rpx;
  574. left: 8rpx;
  575. right: 8rpx;
  576. z-index: 9;
  577. width: auto;
  578. }
  579. .u-error-btn {
  580. color: #ffffff;
  581. background-color: $u-type-error;
  582. font-size: 20rpx;
  583. padding: 4px 0;
  584. text-align: center;
  585. position: absolute;
  586. bottom: 0;
  587. left: 0;
  588. right: 0;
  589. z-index: 9;
  590. line-height: 1;
  591. }
  592. </style>