UploadFile.vue 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <template>
  2. <div class="upload-single">
  3. <el-upload
  4. :ref="refName"
  5. :name="aliasName"
  6. :show-file-list="showFileList"
  7. action=""
  8. :http-request="httpRequest"
  9. :on-change="onChange"
  10. v-bind="$attrs"
  11. >
  12. <el-button icon="el-icon-upload2">{{ btnText }}</el-button>
  13. <slot />
  14. </el-upload>
  15. </div>
  16. </template>
  17. <script>
  18. import { uploadFile } from '@/api/file'
  19. let _uploadId_ = 0
  20. export default {
  21. name: 'UploadFile',
  22. inheritAttrs: false,
  23. props: {
  24. btnText: {
  25. type: String,
  26. default: '上传'
  27. },
  28. fileType: {
  29. type: Number,
  30. default: -1
  31. },
  32. showFileList: {
  33. type: Boolean,
  34. default: false
  35. },
  36. uploadChange: {
  37. type: Function,
  38. default() {}
  39. }
  40. },
  41. data() {
  42. return {
  43. uploadedFile: null,
  44. refName: '_upload_ref_',
  45. aliasName: '_upload_name_'
  46. }
  47. },
  48. created() {
  49. this.initConfig()
  50. },
  51. methods: {
  52. initConfig() {
  53. if (this.$attrs.name) {
  54. this.aliasName = this.$attrs.name
  55. }
  56. this.refName += _uploadId_
  57. this.aliasName += _uploadId_
  58. _uploadId_++
  59. },
  60. onChange(file, fileList) {
  61. if (file.status === 'ready') {
  62. fileList.splice(0, fileList.length - 1)
  63. }
  64. this.uploadChange && this.uploadChange(file)
  65. },
  66. submit() {
  67. this.$refs[this.refName].submit()
  68. },
  69. httpRequest(options) {
  70. const formData = new FormData()
  71. formData.append('file', options.file)
  72. uploadFile(this.fileType, formData).then(res => {
  73. if (options.onSuccess) {
  74. options.onSuccess(res.data)
  75. } else {
  76. console.log(res.data)
  77. }
  78. }).catch(error => {
  79. console.log(error)
  80. options.onError(error)
  81. })
  82. }
  83. }
  84. }
  85. </script>
  86. <style lang="scss" scoped>
  87. .upload-single {
  88. display: inline-block;
  89. }
  90. </style>