upload.vue 19 KB

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