Newer
Older
KaiFengPC / src / components / FileUpload / index.vue
@zhangdeliang zhangdeliang on 23 May 7 KB 初始化项目
  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. :accept="accept.join()"
  15. class="upload-file-uploader"
  16. ref="fileUpload"
  17. :disabled="props.disabled"
  18. >
  19. <!-- 上传按钮 -->
  20. <el-button type="primary">选取文件</el-button>
  21. </el-upload>
  22. <!-- 上传提示 -->
  23. <div class="el-upload__tip" v-if="showTip">
  24. 请上传
  25. <template v-if="fileSize">
  26. 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
  27. </template>
  28. <template v-if="fileType">
  29. 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
  30. </template>
  31. 的文件
  32. </div>
  33. <!-- 文件列表 -->
  34. <transition-group
  35. class="upload-file-list el-upload-list el-upload-list--text"
  36. name="el-fade-in-linear"
  37. tag="ul"
  38. >
  39. <li
  40. :key="file.uid"
  41. :title="file.name"
  42. class="el-upload-list__item ele-upload-list__item-content"
  43. v-for="(file, index) in fileList"
  44. >
  45. <el-link
  46. class="el-icon-document-a"
  47. :href="file.url"
  48. :underline="false"
  49. target="_blank"
  50. @click="handlePreview(file)"
  51. >
  52. <span class="el-icon-document"> {{ file.name }} </span>
  53. </el-link>
  54. <div class="ele-upload-list__item-content-action" v-if="!props.disabled">
  55. <el-link :underline="false" @click="handleDelete(index)" type="danger"
  56. >删除</el-link
  57. >
  58. </div>
  59. </li>
  60. </transition-group>
  61. </div>
  62. </template>
  63.  
  64. <script setup>
  65. import { getToken } from "@/utils/auth";
  66.  
  67. const props = defineProps({
  68. modelValue: [String, Object, Array],
  69. // 数量限制
  70. limit: {
  71. type: Number,
  72. default: 5,
  73. },
  74. // 大小限制(MB)
  75. fileSize: {
  76. type: Number,
  77. default: 0,
  78. },
  79. // 文件类型, 例如['png', 'jpg', 'jpeg']
  80. fileType: {
  81. type: Array,
  82. default: () => ["doc", "xls", "ppt", "txt", "pdf"],
  83. },
  84. // 是否显示提示
  85. isShowTip: {
  86. type: Boolean,
  87. default: true,
  88. },
  89. //是否返回文件名name
  90. isBackName: {
  91. type: Boolean,
  92. default: false,
  93. },
  94. disabled: {
  95. type: Boolean,
  96. default: false
  97. }
  98. });
  99.  
  100. const { proxy } = getCurrentInstance();
  101. const emit = defineEmits();
  102. const number = ref(0);
  103. const uploadList = ref([]);
  104. const baseUrl =
  105. import.meta.env.VITE_APP_ENV == "development"
  106. ? "/dev-api"
  107. : import.meta.env.VITE_APP_BASE_API;
  108. const uploadFileUrl = ref(baseUrl + "/file/upload"); // 上传文件服务器地址
  109. const headers = ref({ Authorization: "Bearer " + getToken() });
  110. const fileList = ref([]);
  111. const showTip = computed(() => {
  112. return props.isShowTip && (props.fileType || props.fileSize);
  113. });
  114.  
  115. watch(
  116. () => props.modelValue,
  117. (val) => {
  118. if (val) {
  119. let temp = 1;
  120. // 首先将值转为数组
  121. const list = Array.isArray(val) ? val : props.modelValue.split(",");
  122. // 然后将数组转为对象数组
  123. fileList.value = list.map((item) => {
  124. if (typeof item === "string") {
  125. item = { name: item, url: item };
  126. }
  127. item.uid = item.uid || new Date().getTime() + temp++;
  128. return item;
  129. });
  130. } else {
  131. fileList.value = [];
  132. return [];
  133. }
  134. },
  135. { deep: true, immediate: true }
  136. );
  137. const accept = computed(() => {
  138. if (props.fileType.length) {
  139. let data = [];
  140. data = props.fileType.map((val) => {
  141. return `.${val}`;
  142. });
  143. return data;
  144. } else {
  145. return [];
  146. }
  147. });
  148. // 上传前校检格式和大小
  149. function handleBeforeUpload(file) {
  150. // 校检文件类型
  151. if (props.fileType.length) {
  152. const fileName = file.name.split(".");
  153. const fileExt = fileName[fileName.length - 1];
  154. const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
  155. if (!isTypeOk) {
  156. proxy.$modal.msgError(
  157. `文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`
  158. );
  159. return false;
  160. }
  161. }
  162. // 校检文件大小
  163. if (props.fileSize) {
  164. const isLt = file.size / 1024 / 1024 < props.fileSize;
  165. if (!isLt) {
  166. proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
  167. return false;
  168. }
  169. }
  170. proxy.$modal.loading("正在上传文件,请稍候...");
  171. number.value++;
  172. return true;
  173. }
  174.  
  175. // 文件个数超出
  176. function handleExceed() {
  177. proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
  178. }
  179.  
  180. // 上传失败
  181. function handleUploadError(err) {
  182. proxy.$modal.msgError("上传文件失败");
  183. }
  184.  
  185. // 上传成功回调
  186. function handleUploadSuccess(res, file) {
  187. if (res.code === 200) {
  188. uploadList.value.push({
  189. name: res.data.url,
  190. url: res.data.url,
  191. originalName: res.data.originalName,
  192. ...res.data
  193. });
  194. uploadedSuccessfully();
  195. } else {
  196. number.value--;
  197. proxy.$modal.closeLoading();
  198. proxy.$modal.msgError(res.msg);
  199. proxy.$refs.fileUpload.handleRemove(file);
  200. uploadedSuccessfully();
  201. }
  202. }
  203.  
  204. // 预览文件
  205. function handlePreview(file) {
  206. emit('preview', file)
  207. }
  208.  
  209. // 删除文件
  210. function handleDelete(index) {
  211. fileList.value.splice(index, 1);
  212. if (props.isBackName) {
  213. emit("update:modelValue", fileList.value);
  214. } else {
  215. emit("update:modelValue", listToString(fileList.value));
  216. }
  217. // emit("update:modelValue", listToString(fileList.value));
  218. }
  219.  
  220. // 上传结束处理
  221. function uploadedSuccessfully() {
  222. if (number.value > 0 && uploadList.value.length === number.value) {
  223. fileList.value = fileList.value
  224. .filter((f) => f.url !== undefined)
  225. .concat(uploadList.value);
  226. console.log("fileList.value", fileList.value);
  227. uploadList.value = [];
  228. number.value = 0;
  229. if (props.isBackName) {
  230. emit("update:modelValue", fileList.value);
  231. } else {
  232. emit("update:modelValue", listToString(fileList.value));
  233. }
  234. // emit("update:modelValue", listToString(fileList.value));
  235. proxy.$modal.closeLoading();
  236. }
  237. }
  238.  
  239. // 获取文件名称
  240. function getFileName(name) {
  241. if (name.lastIndexOf("/") > -1) {
  242. return name.slice(name.lastIndexOf("/") + 1);
  243. } else {
  244. return "";
  245. }
  246. }
  247.  
  248. // 对象转成指定字符串分隔
  249. function listToString(list, separator) {
  250. let strs = "";
  251. separator = separator || ",";
  252. for (let i in list) {
  253. if (list[i].url) {
  254. strs += list[i].url + separator;
  255. }
  256. }
  257. return strs != "" ? strs.substr(0, strs.length - 1) : "";
  258. }
  259. </script>
  260.  
  261. <style scoped lang="scss">
  262. .upload-file {
  263. width: 100%;
  264. }
  265. .upload-file-uploader {
  266. margin-bottom: 5px;
  267. }
  268. .upload-file-list .el-upload-list__item {
  269. border: 1px solid #e4e7ed;
  270. line-height: 2;
  271. margin-bottom: 10px;
  272. position: relative;
  273. }
  274. .upload-file-list .ele-upload-list__item-content {
  275. display: flex;
  276. justify-content: space-between;
  277. align-items: center;
  278. color: inherit;
  279. padding: 5px 10px;
  280. width: 100%;
  281. overflow: hidden;
  282. :deep(.el-icon-document-a){
  283. flex: 1;
  284. overflow: hidden;
  285. .el-link__inner {
  286. white-space: nowrap;
  287. text-overflow: ellipsis;
  288. overflow: hidden;
  289. display: block;
  290. }
  291. }
  292. .ele-upload-list__item-content-action {
  293. flex-shrink: 0;
  294. }
  295. }
  296. .ele-upload-list__item-content-action .el-link {
  297. margin-left: 10px;
  298. }
  299. </style>