u-upload.vue 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  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. console.log(this.formData)
  404. const task = uni.uploadFile({
  405. url: this.action,
  406. filePath: this.lists[index].url,
  407. name: this.name,
  408. formData: this.formData,
  409. header: this.header,
  410. success: res => {
  411. console.log(res)
  412. // 判断是否json字符串,将其转为json格式
  413. let data = this.toJson && this.$u.test.jsonString(res.data) ? JSON.parse(res
  414. .data) : res.data;
  415. if (![200, 201, 204].includes(res.statusCode)) {
  416. this.uploadError(index, data);
  417. } else {
  418. // 上传成功
  419. this.lists[index].response = data;
  420. this.lists[index].progress = 100;
  421. this.lists[index].error = false;
  422. this.lists[index].urlImg = this.formData.domain + '/' + this.formData.key
  423. this.$emit('on-success', data, index, this.lists, this.index);
  424. }
  425. },
  426. fail: e => {
  427. this.uploadError(index, e);
  428. },
  429. complete: res => {
  430. uni.hideLoading();
  431. this.uploading = false;
  432. this.uploadFile(index + 1);
  433. this.$emit('on-change', res, index, this.lists, this.index);
  434. }
  435. });
  436. task.onProgressUpdate(res => {
  437. if (res.progress > 0) {
  438. this.lists[index].progress = res.progress;
  439. this.$emit('on-progress', res, index, this.lists, this.index);
  440. }
  441. });
  442. },
  443. // 上传失败
  444. uploadError(index, err) {
  445. this.lists[index].progress = 0;
  446. this.lists[index].error = true;
  447. this.lists[index].response = null;
  448. this.$emit('on-error', err, index, this.lists, this.index);
  449. this.showToast('上传失败,请重试');
  450. },
  451. // 删除一个图片
  452. deleteItem(index) {
  453. uni.showModal({
  454. title: '提示',
  455. content: '您确定要删除此项吗?',
  456. success: async (res) => {
  457. if (res.confirm) {
  458. // 先检查是否有定义before-remove移除前钩子
  459. // 执行before-remove钩子
  460. if (this.beforeRemove && typeof(this.beforeRemove) === 'function') {
  461. // 此处钩子执行 原理同before-remove参数,见上方注释
  462. let beforeResponse = this.beforeRemove.bind(this.$u.$parent.call(this))(index,
  463. this.lists);
  464. // 判断是否返回了promise
  465. if (!!beforeResponse && typeof beforeResponse.then === 'function') {
  466. await beforeResponse.then(res => {
  467. // promise返回成功,不进行动作,继续上传
  468. this.handlerDeleteItem(index);
  469. }).catch(err => {
  470. // 如果进入promise的reject,终止删除操作
  471. this.showToast('已终止移除');
  472. })
  473. } else if (beforeResponse === false) {
  474. // 返回false,终止删除
  475. this.showToast('已终止移除');
  476. } else {
  477. // 如果返回true,执行删除操作
  478. this.handlerDeleteItem(index);
  479. }
  480. } else {
  481. // 如果不存在before-remove钩子,
  482. this.handlerDeleteItem(index);
  483. }
  484. }
  485. }
  486. });
  487. },
  488. // 执行移除图片的动作,上方代码只是判断是否可以移除
  489. handlerDeleteItem(index) {
  490. // 如果文件正在上传中,终止上传任务,进度在0 < progress < 100则意味着正在上传
  491. if (this.lists[index].process < 100 && this.lists[index].process > 0) {
  492. typeof this.lists[index].uploadTask != 'undefined' && this.lists[index].uploadTask.abort();
  493. }
  494. this.lists.splice(index, 1);
  495. this.$forceUpdate();
  496. this.$emit('on-remove', index, this.lists, this.index);
  497. this.showToast('移除成功');
  498. },
  499. // 用户通过ref手动的形式,移除一张图片
  500. remove(index) {
  501. // 判断索引的合法范围
  502. if (index >= 0 && index < this.lists.length) {
  503. this.lists.splice(index, 1);
  504. this.$emit('on-list-change', this.lists, this.index);
  505. }
  506. },
  507. // 预览图片
  508. doPreviewImage(url, index) {
  509. if (!this.previewFullImage) return;
  510. const images = this.lists.map(item => item.url || item.path);
  511. uni.previewImage({
  512. urls: images,
  513. current: url,
  514. success: () => {
  515. this.$emit('on-preview', url, this.lists, this.index);
  516. },
  517. fail: () => {
  518. uni.showToast({
  519. title: '预览图片失败',
  520. icon: 'none'
  521. });
  522. }
  523. });
  524. },
  525. // 判断文件后缀是否允许
  526. checkFileExt(file) {
  527. // 检查是否在允许的后缀中
  528. let noArrowExt = false;
  529. // 获取后缀名
  530. let fileExt = '';
  531. const reg = /.+\./;
  532. // 如果是H5,需要从name中判断
  533. // #ifdef H5
  534. fileExt = file.name.replace(reg, "").toLowerCase();
  535. // #endif
  536. // 非H5,需要从path中读取后缀
  537. // #ifndef H5
  538. fileExt = file.path.replace(reg, "").toLowerCase();
  539. // #endif
  540. // 使用数组的some方法,只要符合limitType中的一个,就返回true
  541. noArrowExt = this.limitType.some(ext => {
  542. // 转为小写
  543. return ext.toLowerCase() === fileExt;
  544. })
  545. if (!noArrowExt) this.showToast(`不允许选择${fileExt}格式的文件`);
  546. return noArrowExt;
  547. }
  548. }
  549. };
  550. </script>
  551. <style lang="scss" scoped>
  552. @import '../../libs/css/style.components.scss';
  553. .u-upload {
  554. @include vue-flex;
  555. flex-wrap: wrap;
  556. align-items: center;
  557. }
  558. .u-list-item {
  559. width: 200rpx;
  560. height: 200rpx;
  561. overflow: hidden;
  562. margin: 10rpx;
  563. background: rgb(244, 245, 246);
  564. position: relative;
  565. border-radius: 10rpx;
  566. /* #ifndef APP-NVUE */
  567. display: flex;
  568. /* #endif */
  569. align-items: center;
  570. justify-content: center;
  571. }
  572. .u-preview-wrap {
  573. border: 1px solid rgb(235, 236, 238);
  574. }
  575. .u-add-wrap {
  576. flex-direction: column;
  577. color: $u-content-color;
  578. font-size: 26rpx;
  579. }
  580. .u-add-tips {
  581. margin-top: 20rpx;
  582. line-height: 40rpx;
  583. }
  584. .u-add-wrap__hover {
  585. background-color: rgb(235, 236, 238);
  586. }
  587. .u-preview-image {
  588. display: block;
  589. width: 100%;
  590. height: 100%;
  591. border-radius: 10rpx;
  592. }
  593. .u-delete-icon {
  594. position: absolute;
  595. top: 10rpx;
  596. right: 10rpx;
  597. z-index: 10;
  598. background-color: $u-type-error;
  599. border-radius: 100rpx;
  600. width: 44rpx;
  601. height: 44rpx;
  602. @include vue-flex;
  603. align-items: center;
  604. justify-content: center;
  605. }
  606. .u-icon {
  607. @include vue-flex;
  608. align-items: center;
  609. justify-content: center;
  610. }
  611. .u-progress {
  612. position: absolute;
  613. bottom: 10rpx;
  614. left: 8rpx;
  615. right: 8rpx;
  616. z-index: 9;
  617. width: auto;
  618. }
  619. .u-error-btn {
  620. color: #ffffff;
  621. background-color: $u-type-error;
  622. font-size: 20rpx;
  623. padding: 4px 0;
  624. text-align: center;
  625. position: absolute;
  626. bottom: 0;
  627. left: 0;
  628. right: 0;
  629. z-index: 9;
  630. line-height: 1;
  631. }
  632. </style>