u-upload-file.vue 20 KB

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