u-upload.vue 14 KB

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