com-upload.php 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <template id="com-upload">
  2. <div class="com-upload" @click="handleClick">
  3. <slot></slot>
  4. <!-- 文件格式&是否支持多文件上传 -->
  5. <input ref="input" type="file" :accept="accept" :multiple="multiple" style="display: none"
  6. @change="handleChange">
  7. </div>
  8. </template>
  9. <script>
  10. Vue.component('com-upload', {
  11. template: '#com-upload',
  12. props: {
  13. disabled: Boolean,
  14. multiple: Boolean,
  15. max: Number,
  16. accept: String,
  17. params: Object,
  18. fields: Object,
  19. },
  20. data() {
  21. return {
  22. dialogVisible: false,
  23. loading: true,
  24. attachments: [],
  25. checkedAttachments: [],
  26. files: [],
  27. };
  28. },
  29. created() {
  30. },
  31. methods: {
  32. handleClick() {
  33. if (this.disabled) {
  34. return;
  35. }
  36. this.$refs.input.value = null;
  37. this.$refs.input.click();
  38. },
  39. handleChange(e) {
  40. if (!e.target.files) return;
  41. this.uploadFiles(e.target.files);
  42. },
  43. uploadFiles(rawFiles) {
  44. if (this.max && rawFiles.length > this.max) {
  45. this.$message.error('最多一次只能上传' + this.max + '个文件。')
  46. return;
  47. }
  48. this.files = [];
  49. for (let i = 0; i < rawFiles.length; i++) {
  50. const file = {
  51. _complete: false,
  52. response: null,
  53. rawFile: rawFiles[i],
  54. };
  55. this.files.push(file);
  56. }
  57. this.$emit('start', this.files);
  58. // 循环上传文件
  59. for (let i in this.files) {
  60. this.upload(this.files[i]);
  61. }
  62. },
  63. upload(file) {
  64. let formData = new FormData();
  65. const params = {};
  66. params['r'] = 'common/file/upload';
  67. for (let i in this.params) {
  68. params[i] = this.params[i];
  69. }
  70. for (let i in this.fields) {
  71. formData.append(i, this.fields[i]);
  72. }
  73. formData.append('file', file.rawFile, file.rawFile.name);
  74. this.$request({
  75. headers: {'Content-Type': 'multipart/form-data'},
  76. params: params,
  77. method: 'post',
  78. data: formData,
  79. }).then(e => {
  80. if (e.data.code === 1) {
  81. this.$message.error(e.data.msg);
  82. }
  83. file.response = e;
  84. file._complete = true;
  85. this.onSuccess(file);
  86. }).catch(e => {
  87. file._complete = true;
  88. });
  89. },
  90. onSuccess(file) {
  91. // 向父组件传递方法
  92. this.$emit('success', file);
  93. let allComplete = true;
  94. for (let i in this.files) {
  95. if (!this.files[i]._complete) {
  96. allComplete = false;
  97. break;
  98. }
  99. }
  100. if (allComplete) { //全部上传完毕
  101. this.$emit('complete', this.files);
  102. }
  103. },
  104. },
  105. });
  106. </script>