index.vue 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. <template>
  2. <div class="upload-file">
  3. <el-upload
  4. multiple
  5. :action="uploadFileUrl"
  6. :before-upload="handleBeforeUpload"
  7. :file-list="fileList"
  8. :limit="limit"
  9. :on-error="handleUploadError"
  10. :on-exceed="handleExceed"
  11. :on-success="handleUploadSuccess"
  12. :show-file-list="false"
  13. :headers="headers"
  14. class="upload-file-uploader"
  15. ref="fileUpload"
  16. >
  17. <!-- 上传按钮 -->
  18. <el-button size="mini" type="primary">选取文件</el-button>
  19. <!-- 上传提示 -->
  20. <div class="el-upload__tip" slot="tip" v-if="showTip">
  21. 请上传
  22. <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
  23. <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
  24. 的文件
  25. </div>
  26. </el-upload>
  27. <!-- 文件列表 -->
  28. <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
  29. <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
  30. <el-link :href="`${baseUrl}${file.url}`" :underline="false" target="_blank">
  31. <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
  32. </el-link>
  33. <div class="ele-upload-list__item-content-action">
  34. <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
  35. </div>
  36. </li>
  37. </transition-group>
  38. </div>
  39. </template>
  40. <script>
  41. import { getToken } from "@/utils/auth";
  42. export default {
  43. name: "FileUpload",
  44. props: {
  45. // 值
  46. value: [String, Object, Array],
  47. // 数量限制
  48. limit: {
  49. type: Number,
  50. default: 5,
  51. },
  52. // 大小限制(MB)
  53. fileSize: {
  54. type: Number,
  55. default: 5,
  56. },
  57. // 文件类型, 例如['png', 'jpg', 'jpeg']
  58. fileType: {
  59. type: Array,
  60. default: () => ["jpg","png","csv","mat","doc", "xls", "ppt", "txt", "pdf"],
  61. },
  62. // 是否显示提示
  63. isShowTip: {
  64. type: Boolean,
  65. default: true
  66. }
  67. },
  68. data() {
  69. return {
  70. number: 0,
  71. uploadList: [],
  72. baseUrl: process.env.VUE_APP_BASE_API,
  73. uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/customUpload", // 上传文件服务器地址
  74. headers: {
  75. Authorization: "Bearer " + getToken(),
  76. },
  77. fileList: [],
  78. };
  79. },
  80. watch: {
  81. value: {
  82. handler(val) {
  83. if (val) {
  84. let temp = 1;
  85. // 首先将值转为数组
  86. const list = Array.isArray(val) ? val : this.value.split(',');
  87. // 然后将数组转为对象数组
  88. this.fileList = list.map(item => {
  89. if (typeof item === "string") {
  90. item = { name: item, url: item };
  91. }
  92. item.uid = item.uid || new Date().getTime() + temp++;
  93. return item;
  94. });
  95. } else {
  96. this.fileList = [];
  97. return [];
  98. }
  99. },
  100. deep: true,
  101. immediate: true
  102. }
  103. },
  104. computed: {
  105. // 是否显示提示
  106. showTip() {
  107. return this.isShowTip && (this.fileType || this.fileSize);
  108. },
  109. },
  110. methods: {
  111. // 上传前校检格式和大小
  112. handleBeforeUpload(file) {
  113. // 校检文件类型
  114. if (this.fileType) {
  115. const fileName = file.name.split('.');
  116. const fileExt = fileName[fileName.length - 1];
  117. const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
  118. if (!isTypeOk) {
  119. this.$modal.msgError(`文件格式不正确,请上传${this.fileType.join("/")}格式文件!`);
  120. return false;
  121. }
  122. }
  123. // 校检文件名是否包含特殊字符
  124. if (file.name.includes(',')) {
  125. this.$modal.msgError('文件名不正确,不能包含英文逗号!');
  126. return false;
  127. }
  128. // 校检文件大小
  129. if (this.fileSize) {
  130. const isLt = file.size / 1024 / 1024 < this.fileSize;
  131. if (!isLt) {
  132. this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
  133. return false;
  134. }
  135. }
  136. this.$modal.loading("正在上传文件,请稍候...");
  137. this.number++;
  138. return true;
  139. },
  140. // 文件个数超出
  141. handleExceed() {
  142. this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
  143. },
  144. // 上传失败
  145. handleUploadError(err) {
  146. this.$modal.msgError("上传文件失败,请重试");
  147. this.$modal.closeLoading();
  148. },
  149. // 上传成功回调
  150. handleUploadSuccess(res, file) {
  151. if (res.code === 200) {
  152. this.uploadList.push({ name: res.fileName, url: res.fileName });
  153. this.uploadedSuccessfully(res);
  154. } else {
  155. this.number--;
  156. this.$modal.closeLoading();
  157. this.$modal.msgError(res.msg);
  158. this.$refs.fileUpload.handleRemove(file);
  159. this.uploadedSuccessfully();
  160. }
  161. },
  162. // 删除文件
  163. handleDelete(index) {
  164. this.fileList.splice(index, 1);
  165. this.$emit("input", this.listToString(this.fileList));
  166. },
  167. // 上传结束处理
  168. uploadedSuccessfully(res) {
  169. if (this.number > 0 && this.uploadList.length === this.number) {
  170. this.fileList = this.fileList.concat(this.uploadList);
  171. this.uploadList = [];
  172. this.number = 0;
  173. this.$emit('child-event', res)
  174. this.$emit("input", res.url);
  175. this.$modal.closeLoading();
  176. }
  177. },
  178. // 获取文件名称
  179. getFileName(name) {
  180. // 替换连续的斜杠为单个斜杠
  181. const normalizedName = name.replace(/\/+/g, '/');
  182. // 如果是url那么取最后的名字 如果不是直接返回
  183. if (normalizedName.lastIndexOf("/") > -1) {
  184. return normalizedName.slice(normalizedName.lastIndexOf("/") + 1);
  185. } else {
  186. return normalizedName;
  187. }
  188. },
  189. // 对象转成指定字符串分隔
  190. listToString(list, separator) {
  191. let strs = "";
  192. separator = separator || ",";
  193. for (let i in list) {
  194. strs += list[i].url + separator;
  195. }
  196. return strs != '' ? strs.substr(0, strs.length - 1) : '';
  197. }
  198. }
  199. };
  200. </script>
  201. <style scoped lang="scss">
  202. .upload-file-uploader {
  203. margin-bottom: 5px;
  204. }
  205. .upload-file-list .el-upload-list__item {
  206. border: 1px solid #e4e7ed;
  207. line-height: 2;
  208. margin-bottom: 10px;
  209. position: relative;
  210. }
  211. .upload-file-list .ele-upload-list__item-content {
  212. display: flex;
  213. justify-content: space-between;
  214. align-items: center;
  215. color: inherit;
  216. }
  217. .ele-upload-list__item-content-action .el-link {
  218. margin-right: 10px;
  219. }
  220. </style>