FileUpload.vue 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <template>
  2. <el-upload :action="'#'" :http-request="onFileUpload" :accept="fileTypes == null ? '' : fileTypes.join(',')"
  3. :show-file-list="false" :disabled="disabled" :before-upload="beforeUpload" :multiple="true">
  4. <slot></slot>
  5. </el-upload>
  6. </template>
  7. <script>
  8. export default {
  9. name: "fileUpload",
  10. data() {
  11. return {
  12. loading: null,
  13. uploadHeaders: {
  14. "accessToken": sessionStorage.getItem('accessToken')
  15. }
  16. }
  17. },
  18. props: {
  19. action: {
  20. type: String,
  21. required: false
  22. },
  23. fileTypes: {
  24. type: Array,
  25. default: null
  26. },
  27. maxSize: {
  28. type: Number,
  29. default: null
  30. },
  31. showLoading: {
  32. type: Boolean,
  33. default: false
  34. },
  35. isPermanent: {
  36. type: Boolean,
  37. default: false
  38. },
  39. disabled: {
  40. type: Boolean,
  41. default: false
  42. }
  43. },
  44. methods: {
  45. onFileUpload(file) {
  46. // 展示加载条
  47. if (this.showLoading) {
  48. this.loading = this.$loading({
  49. lock: true,
  50. text: '正在上传...',
  51. spinner: 'el-icon-loading',
  52. background: 'rgba(0, 0, 0, 0.7)'
  53. });
  54. }
  55. let formData = new FormData()
  56. formData.append('file', file.file)
  57. let url = this.action;
  58. url += this.action.includes("?") ? "&" : "?"
  59. url += 'isPermanent=' + this.isPermanent;
  60. this.$http({
  61. url: url,
  62. data: formData,
  63. method: 'post',
  64. headers: {
  65. 'Content-Type': 'multipart/form-data'
  66. }
  67. }).then((data) => {
  68. this.$emit("success", data, file.file);
  69. }).catch((e) => {
  70. this.$emit("fail", e, file.file);
  71. }).finally(() => {
  72. this.loading && this.loading.close();
  73. })
  74. },
  75. beforeUpload(file) {
  76. // 校验文件类型
  77. if (this.fileTypes && this.fileTypes.length > 0) {
  78. let fileType = file.type;
  79. let t = this.fileTypes.find((t) => t.toLowerCase() === fileType);
  80. if (t === undefined) {
  81. this.$message.error(`文件格式错误,请上传以下格式的文件:${this.fileTypes.join("、")}`);
  82. return false;
  83. }
  84. }
  85. // 校验大小
  86. if (this.maxSize && file.size > this.maxSize) {
  87. this.$message.error(`文件大小不能超过 ${this.fileSizeStr}!`);
  88. return false;
  89. }
  90. this.$emit("before", file);
  91. return true;
  92. }
  93. },
  94. computed: {
  95. fileSizeStr() {
  96. if (this.maxSize > 1024 * 1024) {
  97. return Math.round(this.maxSize / 1024 / 1024) + "M";
  98. }
  99. if (this.maxSize > 1024) {
  100. return Math.round(this.maxSize / 1024) + "KB";
  101. }
  102. return this.maxSize + "B";
  103. }
  104. }
  105. }
  106. </script>
  107. <style></style>