index.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. <template>
  2. <transition-group class="upload-file-list flex1 ov-hd" :class="{ white }" name="el-fade-in-linear" tag="div">
  3. <el-upload v-if="fileList.length < limit || loading" :multiple="multiple" :action="uploadFileUrl" :before-upload="handleBeforeUpload" :file-list="fileList" :limit="limit" :on-error="handleUploadError" :on-exceed="handleExceed" :on-success="handleUploadSuccess" :show-file-list="false" :headers="headers" :accept="fileType.map(item => '.'+ item).toString()" class="upload-file-uploader" ref="fileUploadRef" :on-progress="handleOnProgress">
  4. <!-- 上传按钮 -->
  5. <!-- <div class="btn-file f-14 c-666">上传</div> -->
  6. <el-button class="h-plain mb10" type="primary" plain>
  7. <el-icon><Upload /></el-icon>
  8. {{ btnText }}
  9. </el-button>
  10. </el-upload>
  11. <el-row :gutter="60">
  12. <el-col :span="span" v-for="(file, index) in fileList" :key="index">
  13. <div class="upload-list-img d-flex a-c" :class="{ mt10: index }">
  14. <template v-if="file.url">
  15. <a v-if="['png', 'jpg', 'jpeg', 'bmp'].includes(fileExt(file.name))" class="flex1 right-wrap ov-hd" @click="show2 = true; lookIndex = index">
  16. <el-tooltip class="box-item" effect="dark" :content="file.name" placement="top">
  17. <div class="item-text sv-1 flex1">{{ file.name }}</div>
  18. </el-tooltip>
  19. </a>
  20. <a v-else class="flex1 right-wrap ov-hd" :href="`${file.url}`" :underline="false" target="_blank">
  21. <el-tooltip class="box-item" effect="dark" :content="file.name" placement="top">
  22. <div class="item-text sv-1 flex1">{{ file.name || '-' }}</div>
  23. </el-tooltip>
  24. </a>
  25. </template>
  26. <div v-else class="flex1 right-wrap ov-hd p-rtv">
  27. <el-tooltip class="box-item" effect="dark" :content="file.name" placement="top">
  28. <div class="item-text sv-1">{{ file.name || '-' }}</div>
  29. </el-tooltip>
  30. <div class="progress" :style="{ width: file.percentage + '%' }"></div>
  31. </div>
  32. <div class="delete-item d-flex a-c j-c" @click="handleDelete(index)">
  33. <el-icon color="#FF3A3A" :size="20"><Close /></el-icon>
  34. </div>
  35. </div>
  36. </el-col>
  37. <el-col v-if="isShowTip" :span="span">
  38. <div class="c-999 f-12" style="line-height: 1.6;padding-top: 10px;">
  39. {{ tipText }}
  40. </div>
  41. </el-col>
  42. </el-row>
  43. </transition-group>
  44. <ImageViewer v-model:show="show2" :imgs="fileList.map((item: any) => item.url)" :index="lookIndex"></ImageViewer>
  45. </template>
  46. <script setup lang="ts">
  47. import { listByIds, delOss } from '@/api/system/oss';
  48. import { propTypes } from '@/utils/propTypes';
  49. import { globalHeaders } from '@/utils/request';
  50. import { fileExt } from '@/utils/ruoyi';
  51. import { ImageViewer } from '@/views/models';
  52. const props = defineProps({
  53. modelValue: [String, Object, Array],
  54. // 数量限制
  55. limit: propTypes.number.def(1),
  56. // 大小限制(MB)
  57. fileSize: propTypes.number.def(5),
  58. // 文件类型, 例如['png', 'jpg', 'jpeg', 'bmp']
  59. fileType: propTypes.array.def(['doc', 'xls', 'ppt', 'txt', 'pdf', 'xlsx', 'docx', 'pptx', 'DOCX', 'DOC', 'PPTX', 'PPT']),
  60. // 是否显示提示
  61. isShowTip: propTypes.bool.def(true),
  62. tipText: propTypes.string.def(''),
  63. span: propTypes.number.def(24),
  64. multiple: propTypes.bool.def(true),
  65. white: propTypes.bool.def(false),
  66. // 上传数据格式
  67. format: propTypes.string.def('id'),
  68. btnText: propTypes.string.def('上传文件')
  69. });
  70. const loading = ref(false);
  71. const lookIndex = ref(0);
  72. const show2 = ref(false);
  73. const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  74. const emit = defineEmits(['update:modelValue', 'change']);
  75. const number = ref(0);
  76. const uploadList = ref<any[]>([]);
  77. const baseUrl = import.meta.env.VITE_APP_BASE_API;
  78. const uploadFileUrl = ref(baseUrl + '/resource/oss/upload'); // 上传文件服务器地址
  79. const headers = ref(globalHeaders());
  80. const fileList = ref<any[]>([]);
  81. const showTip = computed(() => props.isShowTip && (props.fileType || props.fileSize));
  82. const fileUploadRef = ref<ElUploadInstance>();
  83. const progressList = ref<any>([]);
  84. const formatValue = ref(props.format);
  85. watch(
  86. () => props.modelValue,
  87. async (val: any) => {
  88. if (val) {
  89. let temp = 1;
  90. // 首先将值转为数组
  91. let list = [];
  92. if (props.format === 'array' || Array.isArray(val)) {
  93. formatValue.value = 'array';
  94. list = val;
  95. } else if (props.format === 'object' || typeof val === 'object') {
  96. formatValue.value = 'object';
  97. list = [
  98. {
  99. name: val.fileName,
  100. url: val.url,
  101. fileSize: val.fileSize,
  102. fileType: val.fileType,
  103. ossId: val.ossId
  104. }
  105. ];
  106. } else {
  107. // 是否http开头
  108. formatValue.value = 'id';
  109. const res = await listByIds(val as string);
  110. list = res.data.map((oss) => {
  111. const data = { name: oss.originalName, url: oss.url, ossId: oss.ossId };
  112. return data;
  113. });
  114. }
  115. // 然后将数组转为对象数组
  116. fileList.value = list.map((item) => {
  117. item = { name: item.fileName ? item.fileName : item.name, url: item.url, fileSize: item.fileSize, fileType: item.fileType };
  118. item.uid = item.uid || new Date().getTime() + temp++;
  119. return item;
  120. });
  121. } else {
  122. fileList.value = [];
  123. return [];
  124. }
  125. },
  126. { deep: true, immediate: true }
  127. );
  128. // 上传前校检格式和大小
  129. const handleBeforeUpload = (file: any) => {
  130. // 校检文件类型
  131. if (props.fileType.length) {
  132. loading.value = true;
  133. const fileName = file.name.split('.');
  134. const fileExt = fileName[fileName.length - 1];
  135. const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
  136. if (!isTypeOk) {
  137. proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}格式文件!`);
  138. loading.value = false;
  139. return false;
  140. }
  141. }
  142. // 校检文件大小
  143. if (props.fileSize) {
  144. const isLt = file.size / 1024 / 1024 < props.fileSize;
  145. if (!isLt) {
  146. loading.value = false;
  147. proxy?.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
  148. return false;
  149. }
  150. }
  151. number.value++;
  152. return true;
  153. };
  154. // 文件个数超出
  155. const handleExceed = () => {
  156. proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
  157. };
  158. // 上传失败
  159. const handleUploadError = () => {
  160. loading.value = false;
  161. proxy?.$modal.msgError('上传文件失败');
  162. };
  163. // 上传成功回调
  164. const handleUploadSuccess = (res: any, file: UploadFile) => {
  165. loading.value = false;
  166. if (res.code === 200) {
  167. uploadList.value.push({
  168. name: res.data.fileName,
  169. url: res.data.url,
  170. ossId: res.data.ossId,
  171. fileSize: file?.raw.size,
  172. fileType: file?.raw.type
  173. });
  174. uploadedSuccessfully();
  175. } else {
  176. number.value--;
  177. proxy?.$modal.msgError(res.msg);
  178. fileUploadRef.value?.handleRemove(file);
  179. uploadedSuccessfully();
  180. }
  181. };
  182. // 上传结束处理
  183. const uploadedSuccessfully = () => {
  184. if (number.value > 0 && uploadList.value.length === number.value) {
  185. fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);
  186. uploadList.value = [];
  187. number.value = 0;
  188. const valuef = fileList.value.map(({ name, url, fileType, fileSize, ossId }) => ({ fileName: name, url, fileSize, fileType, ossId }));
  189. if (formatValue.value === 'id') {
  190. emit('change', listToString(valuef));
  191. emit('update:modelValue', listToString(valuef));
  192. } else if (formatValue.value === 'object') {
  193. emit('change', valuef[0]);
  194. emit('update:modelValue', valuef[0]);
  195. } else {
  196. emit('change', valuef);
  197. emit('update:modelValue', valuef);
  198. }
  199. }
  200. };
  201. const handleOnProgress = (event: any, file: any, list: any) => {
  202. const progress = Math.round((event.loaded / event.total) * 100);
  203. fileList.value = [...list];
  204. };
  205. // 删除文件
  206. const handleDelete = (index: number) => {
  207. fileUploadRef.value?.abort(fileList.value[index]);
  208. fileList.value.splice(index, 1);
  209. const valuef = fileList.value.map(({ name, url, fileType, fileSize }) => ({ fileName: name, url, fileSize, fileType }));
  210. if (formatValue.value === 'id') {
  211. emit('change', listToString(valuef));
  212. emit('update:modelValue', listToString(valuef));
  213. } else if (formatValue.value === 'object') {
  214. emit('change', null);
  215. emit('update:modelValue', null);
  216. } else {
  217. emit('change', valuef);
  218. emit('update:modelValue', valuef);
  219. }
  220. loading.value = false;
  221. };
  222. // 获取文件名称
  223. const getFileName = (name: string) => {
  224. // 如果是url那么取最后的名字 如果不是直接返回
  225. if (name.lastIndexOf('/') > -1) {
  226. return name.slice(name.lastIndexOf('/') + 1);
  227. } else {
  228. return name;
  229. }
  230. };
  231. // 对象转成指定字符串分隔
  232. const listToString = (list: any[], separator?: string) => {
  233. let strs = '';
  234. separator = separator || ',';
  235. list.forEach((item) => {
  236. if (item.ossId) {
  237. strs += item.ossId + separator;
  238. }
  239. });
  240. return strs != '' ? strs.substring(0, strs.length - 1) : '';
  241. };
  242. </script>
  243. <style scoped lang="scss">
  244. .btn-file {
  245. width: 90px;
  246. height: 40px;
  247. line-height: 40px;
  248. border-radius: 8px;
  249. color: #666;
  250. text-align: center;
  251. background-color: #f7f7f7;
  252. }
  253. .upload-list-img {
  254. background-color: #f7f7f7;
  255. border-radius: 8px;
  256. &.mt10 {
  257. margin-top: 10px;
  258. }
  259. }
  260. .right-item {
  261. padding: 10px 16px;
  262. cursor: pointer;
  263. &:hover {
  264. color: var(--el-color-primary);
  265. }
  266. }
  267. .delete-item {
  268. width: 40px;
  269. cursor: pointer;
  270. }
  271. .upload-file-list.white {
  272. .btn-file {
  273. background-color: #fff;
  274. }
  275. .upload-list-img {
  276. background-color: #fff;
  277. }
  278. }
  279. .right-wrap {
  280. padding: 6px 10px;
  281. box-sizing: border-box;
  282. }
  283. .progress {
  284. position: absolute;
  285. left: 0;
  286. bottom: 0;
  287. height: 1px;
  288. background-color: var(--el-color-primary);
  289. }
  290. </style>