u-upload.vue 19 KB

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