file-upload.vue 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <template>
  2. <view>
  3. <lsj-upload ref="lsjUpload" :height="'100%'" :option="option" @uploadEnd="onUploadEnd" @change="onChange"
  4. :size="maxSize" :instantly="true">
  5. <slot></slot>
  6. </lsj-upload>
  7. </view>
  8. </template>
  9. <script>
  10. import UNI_APP from '@/.env.js';
  11. export default {
  12. name: "file-upload",
  13. data() {
  14. return {
  15. fileMap: new Map(),
  16. option: {
  17. url: UNI_APP.BASE_URL + '/file/upload',
  18. name: 'file'
  19. }
  20. }
  21. },
  22. props: {
  23. maxSize: {
  24. type: Number,
  25. default: 10
  26. },
  27. onBefore: {
  28. type: Function,
  29. default: null
  30. },
  31. onSuccess: {
  32. type: Function,
  33. default: null
  34. },
  35. onError: {
  36. type: Function,
  37. default: null
  38. }
  39. },
  40. methods: {
  41. show() {
  42. this.$refs.lsjUpload.show();
  43. },
  44. hide() {
  45. this.$refs.lsjUpload.hide();
  46. },
  47. onUploadEnd(item) {
  48. let file = this.fileMap.get(item.path);
  49. if (item.type == 'fail') {
  50. this.onError(file)
  51. return;
  52. }
  53. let res = JSON.parse(item.responseText);
  54. if (res.code == 200) {
  55. // 上传成功
  56. this.onOk(file, res);
  57. } else {
  58. // 上传失败
  59. this.onError(file, res);
  60. }
  61. },
  62. onChange(files) {
  63. if (!files.size) {
  64. return;
  65. }
  66. files.forEach((file, name) => {
  67. if (!this.fileMap.has(file.path)) {
  68. this.onBefore && this.onBefore(file)
  69. this.fileMap.set(file.path, file);
  70. }
  71. })
  72. },
  73. onOk(file, res) {
  74. this.fileMap.delete(file.path);
  75. this.$refs.lsjUpload.clear(file.name);
  76. this.onSuccess && this.onSuccess(file, res);
  77. },
  78. onFailed(file, res) {
  79. this.fileMap.delete(file.path);
  80. this.$refs.lsjUpload.clear(file.name);
  81. this.onError && this.onError(file, res);
  82. }
  83. }
  84. }
  85. </script>
  86. <style></style>