u-upload.vue 20 KB

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