s-uploader.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. <!-- 文件上传,基于 upload-file 和 upload-image 实现 -->
  2. <template>
  3. <view class="uni-file-picker">
  4. <view v-if="title" class="uni-file-picker__header">
  5. <text class="file-title">{{ title }}</text>
  6. <text class="file-count">{{ filesList.length }}/{{ limitLength }}</text>
  7. </view>
  8. <view v-if="subtitle" class="file-subtitle">
  9. <view>{{ subtitle }}</view>
  10. </view>
  11. <upload-image
  12. v-if="fileMediatype === 'image' && showType === 'grid'"
  13. :readonly="readonly"
  14. :image-styles="imageStyles"
  15. :files-list="url"
  16. :limit="limitLength"
  17. :disablePreview="disablePreview"
  18. :delIcon="delIcon"
  19. @uploadFiles="uploadFiles"
  20. @choose="choose"
  21. @delFile="delFile"
  22. >
  23. <slot>
  24. <view class="is-add">
  25. <image :src="imgsrc" class="add-icon"></image>
  26. </view>
  27. </slot>
  28. </upload-image>
  29. <upload-file
  30. v-if="fileMediatype !== 'image' || showType !== 'grid'"
  31. :readonly="readonly"
  32. :list-styles="listStyles"
  33. :files-list="filesList"
  34. :showType="showType"
  35. :delIcon="delIcon"
  36. @uploadFiles="uploadFiles"
  37. @choose="choose"
  38. @delFile="delFile"
  39. >
  40. <slot><button type="primary" size="mini">选择文件</button></slot>
  41. </upload-file>
  42. </view>
  43. </template>
  44. <script>
  45. import { chooseAndUploadFile, uploadCloudFiles } from './choose-and-upload-file.js';
  46. import { get_extname, get_files_and_is_max, get_file_data } from './utils.js';
  47. import uploadImage from './upload-image.vue';
  48. import uploadFile from './upload-file.vue';
  49. import sheep from '@/sheep';
  50. let fileInput = null;
  51. /**
  52. * FilePicker 文件选择上传
  53. * @description 文件选择上传组件,可以选择图片、视频等任意文件并上传到当前绑定的服务空间
  54. * @tutorial https://ext.dcloud.net.cn/plugin?id=4079
  55. * @property {Object|Array} value 组件数据,通常用来回显 ,类型由return-type属性决定
  56. * @property {String|Array} url url数据
  57. * @property {Boolean} disabled = [true|false] 组件禁用
  58. * @value true 禁用
  59. * @value false 取消禁用
  60. * @property {Boolean} readonly = [true|false] 组件只读,不可选择,不显示进度,不显示删除按钮
  61. * @value true 只读
  62. * @value false 取消只读
  63. * @property {Boolean} disable-preview = [true|false] 禁用图片预览,仅 mode:grid 时生效
  64. * @value true 禁用图片预览
  65. * @value false 取消禁用图片预览
  66. * @property {Boolean} del-icon = [true|false] 是否显示删除按钮
  67. * @value true 显示删除按钮
  68. * @value false 不显示删除按钮
  69. * @property {Boolean} auto-upload = [true|false] 是否自动上传,值为true则只触发@select,可自行上传
  70. * @value true 自动上传
  71. * @value false 取消自动上传
  72. * @property {Number|String} limit 最大选择个数 ,h5 会自动忽略多选的部分
  73. * @property {String} title 组件标题,右侧显示上传计数
  74. * @property {String} mode = [list|grid] 选择文件后的文件列表样式
  75. * @value list 列表显示
  76. * @value grid 宫格显示
  77. * @property {String} file-mediatype = [image|video|all] 选择文件类型
  78. * @value image 只选择图片
  79. * @value video 只选择视频
  80. * @value all 选择所有文件
  81. * @property {Array} file-extname 选择文件后缀,根据 file-mediatype 属性而不同
  82. * @property {Object} list-style mode:list 时的样式
  83. * @property {Object} image-styles 选择文件后缀,根据 file-mediatype 属性而不同
  84. * @event {Function} select 选择文件后触发
  85. * @event {Function} progress 文件上传时触发
  86. * @event {Function} success 上传成功触发
  87. * @event {Function} fail 上传失败触发
  88. * @event {Function} delete 文件从列表移除时触发
  89. */
  90. export default {
  91. name: 'sUploader',
  92. components: {
  93. uploadImage,
  94. uploadFile,
  95. },
  96. options: {
  97. virtualHost: true,
  98. },
  99. emits: ['select', 'success', 'fail', 'progress', 'delete', 'update:modelValue', 'update:url'],
  100. props: {
  101. modelValue: {
  102. type: [Array, Object],
  103. default() {
  104. return [];
  105. },
  106. },
  107. url: {
  108. type: [Array, String],
  109. default() {
  110. return [];
  111. },
  112. },
  113. disabled: {
  114. type: Boolean,
  115. default: false,
  116. },
  117. disablePreview: {
  118. type: Boolean,
  119. default: false,
  120. },
  121. delIcon: {
  122. type: Boolean,
  123. default: true,
  124. },
  125. // 自动上传
  126. autoUpload: {
  127. type: Boolean,
  128. default: true,
  129. },
  130. // 最大选择个数 ,h5只能限制单选或是多选
  131. limit: {
  132. type: [Number, String],
  133. default: 9,
  134. },
  135. // 列表样式 grid | list | list-card
  136. mode: {
  137. type: String,
  138. default: 'grid',
  139. },
  140. // 选择文件类型 image/video/all
  141. fileMediatype: {
  142. type: String,
  143. default: 'image',
  144. },
  145. // 文件类型筛选
  146. fileExtname: {
  147. type: [Array, String],
  148. default() {
  149. return [];
  150. },
  151. },
  152. title: {
  153. type: String,
  154. default: '',
  155. },
  156. listStyles: {
  157. type: Object,
  158. default() {
  159. return {
  160. // 是否显示边框
  161. border: true,
  162. // 是否显示分隔线
  163. dividline: true,
  164. // 线条样式
  165. borderStyle: {},
  166. };
  167. },
  168. },
  169. imageStyles: {
  170. type: Object,
  171. default() {
  172. return {
  173. width: 'auto',
  174. height: 'auto',
  175. };
  176. },
  177. },
  178. readonly: {
  179. type: Boolean,
  180. default: false,
  181. },
  182. sizeType: {
  183. type: Array,
  184. default() {
  185. return ['original', 'compressed'];
  186. },
  187. },
  188. driver: {
  189. type: String,
  190. default: 'local', // local=本地 | oss | unicloud
  191. },
  192. subtitle: {
  193. type: String,
  194. default: '',
  195. },
  196. },
  197. data() {
  198. return {
  199. files: [],
  200. localValue: [],
  201. imgsrc: sheep.$url.static('/static/img/shop/upload-camera.png'),
  202. };
  203. },
  204. watch: {
  205. modelValue: {
  206. handler(newVal, oldVal) {
  207. this.setValue(newVal, oldVal);
  208. },
  209. immediate: true,
  210. },
  211. },
  212. computed: {
  213. returnType() {
  214. if (this.limit > 1) {
  215. return 'array';
  216. }
  217. return 'object';
  218. },
  219. filesList() {
  220. let files = [];
  221. this.files.forEach((v) => {
  222. files.push(v);
  223. });
  224. return files;
  225. },
  226. showType() {
  227. if (this.fileMediatype === 'image') {
  228. return this.mode;
  229. }
  230. return 'list';
  231. },
  232. limitLength() {
  233. if (this.returnType === 'object') {
  234. return 1;
  235. }
  236. if (!this.limit) {
  237. return 1;
  238. }
  239. if (this.limit >= 9) {
  240. return 9;
  241. }
  242. return this.limit;
  243. },
  244. },
  245. created() {
  246. if (this.driver === 'local') {
  247. uniCloud.chooseAndUploadFile = chooseAndUploadFile;
  248. }
  249. this.form = this.getForm('uniForms');
  250. this.formItem = this.getForm('uniFormsItem');
  251. if (this.form && this.formItem) {
  252. if (this.formItem.name) {
  253. this.rename = this.formItem.name;
  254. this.form.inputChildrens.push(this);
  255. }
  256. }
  257. },
  258. methods: {
  259. /**
  260. * 公开用户使用,清空文件
  261. * @param {Object} index
  262. */
  263. clearFiles(index) {
  264. if (index !== 0 && !index) {
  265. this.files = [];
  266. this.$nextTick(() => {
  267. this.setEmit();
  268. });
  269. } else {
  270. this.files.splice(index, 1);
  271. }
  272. this.$nextTick(() => {
  273. this.setEmit();
  274. });
  275. },
  276. /**
  277. * 公开用户使用,继续上传
  278. */
  279. upload() {
  280. let files = [];
  281. this.files.forEach((v, index) => {
  282. if (v.status === 'ready' || v.status === 'error') {
  283. files.push(Object.assign({}, v));
  284. }
  285. });
  286. return this.uploadFiles(files);
  287. },
  288. async setValue(newVal, oldVal) {
  289. const newData = async (v) => {
  290. const reg = /cloud:\/\/([\w.]+\/?)\S*/;
  291. let url = '';
  292. if (v.fileID) {
  293. url = v.fileID;
  294. } else {
  295. url = v.url;
  296. }
  297. if (reg.test(url)) {
  298. v.fileID = url;
  299. v.url = await this.getTempFileURL(url);
  300. }
  301. if (v.url) v.path = v.url;
  302. return v;
  303. };
  304. if (this.returnType === 'object') {
  305. if (newVal) {
  306. await newData(newVal);
  307. } else {
  308. newVal = {};
  309. }
  310. } else {
  311. if (!newVal) newVal = [];
  312. for (let i = 0; i < newVal.length; i++) {
  313. let v = newVal[i];
  314. await newData(v);
  315. }
  316. }
  317. this.localValue = newVal;
  318. if (this.form && this.formItem && !this.is_reset) {
  319. this.is_reset = false;
  320. this.formItem.setValue(this.localValue);
  321. }
  322. let filesData = Object.keys(newVal).length > 0 ? newVal : [];
  323. this.files = [].concat(filesData);
  324. },
  325. /**
  326. * 选择文件
  327. */
  328. choose() {
  329. if (this.disabled) return;
  330. if (
  331. this.files.length >= Number(this.limitLength) &&
  332. this.showType !== 'grid' &&
  333. this.returnType === 'array'
  334. ) {
  335. uni.showToast({
  336. title: `您最多选择 ${this.limitLength} 个文件`,
  337. icon: 'none',
  338. });
  339. return;
  340. }
  341. this.chooseFiles();
  342. },
  343. /**
  344. * 选择文件并上传
  345. */
  346. async chooseFiles() {
  347. const _extname = get_extname(this.fileExtname);
  348. // 获取后缀
  349. await chooseAndUploadFile({
  350. type: this.fileMediatype,
  351. compressed: false,
  352. sizeType: this.sizeType,
  353. // TODO 如果为空,video 有问题
  354. extension: _extname.length > 0 ? _extname : undefined,
  355. count: this.limitLength - this.files.length, //默认9
  356. onChooseFile: this.chooseFileCallback,
  357. onUploadProgress: (progressEvent) => {
  358. this.setProgress(progressEvent, progressEvent.index);
  359. },
  360. })
  361. .then((result) => {
  362. this.setSuccessAndError(result);
  363. })
  364. .catch((err) => {
  365. console.log('选择失败', err);
  366. });
  367. },
  368. /**
  369. * 选择文件回调
  370. * @param {Object} res
  371. */
  372. async chooseFileCallback(res) {
  373. const _extname = get_extname(this.fileExtname);
  374. const is_one =
  375. (Number(this.limitLength) === 1 && this.disablePreview && !this.disabled) ||
  376. this.returnType === 'object';
  377. // 如果这有一个文件 ,需要清空本地缓存数据
  378. if (is_one) {
  379. this.files = [];
  380. }
  381. let { filePaths, files } = get_files_and_is_max(res, _extname);
  382. if (!(_extname && _extname.length > 0)) {
  383. filePaths = res.tempFilePaths;
  384. files = res.tempFiles;
  385. }
  386. let currentData = [];
  387. for (let i = 0; i < files.length; i++) {
  388. if (this.limitLength - this.files.length <= 0) break;
  389. files[i].uuid = Date.now();
  390. let filedata = await get_file_data(files[i], this.fileMediatype);
  391. filedata.progress = 0;
  392. filedata.status = 'ready';
  393. this.files.push(filedata);
  394. currentData.push({
  395. ...filedata,
  396. file: files[i],
  397. });
  398. }
  399. this.$emit('select', {
  400. tempFiles: currentData,
  401. tempFilePaths: filePaths,
  402. });
  403. res.tempFiles = files;
  404. // 停止自动上传
  405. if (!this.autoUpload) {
  406. res.tempFiles = [];
  407. }
  408. },
  409. /**
  410. * 批传
  411. * @param {Object} e
  412. */
  413. uploadFiles(files) {
  414. files = [].concat(files);
  415. return uploadCloudFiles
  416. .call(this, files, 5, (res) => {
  417. this.setProgress(res, res.index, true);
  418. })
  419. .then((result) => {
  420. this.setSuccessAndError(result);
  421. return result;
  422. })
  423. .catch((err) => {
  424. console.log(err);
  425. });
  426. },
  427. /**
  428. * 成功或失败
  429. */
  430. async setSuccessAndError(res, fn) {
  431. let successData = [];
  432. let errorData = [];
  433. let tempFilePath = [];
  434. let errorTempFilePath = [];
  435. for (let i = 0; i < res.length; i++) {
  436. const item = res[i];
  437. const index = item.uuid ? this.files.findIndex((p) => p.uuid === item.uuid) : item.index;
  438. if (index === -1 || !this.files) break;
  439. if (item.errMsg === 'request:fail') {
  440. this.files[index].url = item.url;
  441. this.files[index].status = 'error';
  442. this.files[index].errMsg = item.errMsg;
  443. // this.files[index].progress = -1
  444. errorData.push(this.files[index]);
  445. errorTempFilePath.push(this.files[index].url);
  446. } else {
  447. this.files[index].errMsg = '';
  448. this.files[index].fileID = item.url;
  449. const reg = /cloud:\/\/([\w.]+\/?)\S*/;
  450. if (reg.test(item.url)) {
  451. this.files[index].url = await this.getTempFileURL(item.url);
  452. } else {
  453. this.files[index].url = item.url;
  454. }
  455. this.files[index].status = 'success';
  456. this.files[index].progress += 1;
  457. successData.push(this.files[index]);
  458. tempFilePath.push(this.files[index].fileID);
  459. }
  460. }
  461. if (successData.length > 0) {
  462. this.setEmit();
  463. // 状态改变返回
  464. this.$emit('success', {
  465. tempFiles: this.backObject(successData),
  466. tempFilePaths: tempFilePath,
  467. });
  468. }
  469. if (errorData.length > 0) {
  470. this.$emit('fail', {
  471. tempFiles: this.backObject(errorData),
  472. tempFilePaths: errorTempFilePath,
  473. });
  474. }
  475. },
  476. /**
  477. * 获取进度
  478. * @param {Object} progressEvent
  479. * @param {Object} index
  480. * @param {Object} type
  481. */
  482. setProgress(progressEvent, index, type) {
  483. const fileLenth = this.files.length;
  484. const percentNum = (index / fileLenth) * 100;
  485. const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
  486. let idx = index;
  487. if (!type) {
  488. idx = this.files.findIndex((p) => p.uuid === progressEvent.tempFile.uuid);
  489. }
  490. if (idx === -1 || !this.files[idx]) return;
  491. // fix by mehaotian 100 就会消失,-1 是为了让进度条消失
  492. this.files[idx].progress = percentCompleted - 1;
  493. // 上传中
  494. this.$emit('progress', {
  495. index: idx,
  496. progress: parseInt(percentCompleted),
  497. tempFile: this.files[idx],
  498. });
  499. },
  500. /**
  501. * 删除文件
  502. * @param {Object} index
  503. */
  504. delFile(index) {
  505. this.$emit('delete', {
  506. tempFile: this.files[index],
  507. tempFilePath: this.files[index].url,
  508. });
  509. this.files.splice(index, 1);
  510. this.$nextTick(() => {
  511. this.setEmit();
  512. });
  513. },
  514. /**
  515. * 获取文件名和后缀
  516. * @param {Object} name
  517. */
  518. getFileExt(name) {
  519. const last_len = name.lastIndexOf('.');
  520. const len = name.length;
  521. return {
  522. name: name.substring(0, last_len),
  523. ext: name.substring(last_len + 1, len),
  524. };
  525. },
  526. /**
  527. * 处理返回事件
  528. */
  529. setEmit() {
  530. let data = [];
  531. let updateUrl = [];
  532. if (this.returnType === 'object') {
  533. data = this.backObject(this.files)[0];
  534. this.localValue = data ? data : null;
  535. updateUrl = data ? data.url : '';
  536. } else {
  537. data = this.backObject(this.files);
  538. if (!this.localValue) {
  539. this.localValue = [];
  540. }
  541. this.localValue = [...data];
  542. if (this.localValue.length > 0) {
  543. this.localValue.forEach((item) => {
  544. updateUrl.push(item.url);
  545. });
  546. }
  547. }
  548. this.$emit('update:modelValue', this.localValue);
  549. this.$emit('update:url', updateUrl);
  550. },
  551. /**
  552. * 处理返回参数
  553. * @param {Object} files
  554. */
  555. backObject(files) {
  556. let newFilesData = [];
  557. files.forEach((v) => {
  558. newFilesData.push({
  559. extname: v.extname,
  560. fileType: v.fileType,
  561. image: v.image,
  562. name: v.name,
  563. path: v.path,
  564. size: v.size,
  565. fileID: v.fileID,
  566. url: v.url,
  567. });
  568. });
  569. return newFilesData;
  570. },
  571. async getTempFileURL(fileList) {
  572. fileList = {
  573. fileList: [].concat(fileList),
  574. };
  575. const urls = await uniCloud.getTempFileURL(fileList);
  576. return urls.fileList[0].tempFileURL || '';
  577. },
  578. /**
  579. * 获取父元素实例
  580. */
  581. getForm(name = 'uniForms') {
  582. let parent = this.$parent;
  583. let parentName = parent.$options.name;
  584. while (parentName !== name) {
  585. parent = parent.$parent;
  586. if (!parent) return false;
  587. parentName = parent.$options.name;
  588. }
  589. return parent;
  590. },
  591. },
  592. };
  593. </script>
  594. <style lang="scss" scoped>
  595. .uni-file-picker {
  596. /* #ifndef APP-NVUE */
  597. box-sizing: border-box;
  598. overflow: hidden;
  599. /* width: 100%; */
  600. /* #endif */
  601. /* flex: 1; */
  602. position: relative;
  603. }
  604. .uni-file-picker__header {
  605. padding-top: 5px;
  606. padding-bottom: 10px;
  607. /* #ifndef APP-NVUE */
  608. display: flex;
  609. /* #endif */
  610. justify-content: space-between;
  611. }
  612. .file-title {
  613. font-size: 14px;
  614. color: #333;
  615. }
  616. .file-count {
  617. font-size: 14px;
  618. color: #999;
  619. }
  620. .is-add {
  621. /* #ifndef APP-NVUE */
  622. display: flex;
  623. /* #endif */
  624. align-items: center;
  625. justify-content: center;
  626. }
  627. .add-icon {
  628. width: 57rpx;
  629. height: 49rpx;
  630. }
  631. .file-subtitle {
  632. position: absolute;
  633. left: 50%;
  634. transform: translateX(-50%);
  635. bottom: 0;
  636. width: 140rpx;
  637. height: 36rpx;
  638. z-index: 1;
  639. display: flex;
  640. justify-content: center;
  641. color: #fff;
  642. font-weight: 500;
  643. background: rgba(#000, 0.3);
  644. font-size: 24rpx;
  645. }
  646. </style>