index.vue 6.7 KB

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