index.vue 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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']),
  60. // 是否显示提示
  61. isShowTip: propTypes.bool.def(true),
  62. tipText: propTypes.string.def(''),
  63. span: propTypes.number.def(24),
  64. isObject: propTypes.bool.def(false),
  65. multiple: propTypes.bool.def(true),
  66. white: propTypes.bool.def(false),
  67. // 上传数据格式
  68. format: propTypes.string.def('id'),
  69. btnText: propTypes.string.def('上传文件')
  70. });
  71. const loading = ref(false);
  72. const lookIndex = ref(0);
  73. const show2 = ref(false);
  74. const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  75. const emit = defineEmits(['update:modelValue', 'change']);
  76. const number = ref(0);
  77. const uploadList = ref<any[]>([]);
  78. const baseUrl = import.meta.env.VITE_APP_BASE_API;
  79. const uploadFileUrl = ref(baseUrl + '/resource/oss/upload'); // 上传文件服务器地址
  80. const headers = ref(globalHeaders());
  81. const fileList = ref<any[]>([]);
  82. const showTip = computed(() => props.isShowTip && (props.fileType || props.fileSize));
  83. const fileUploadRef = ref<ElUploadInstance>();
  84. const progressList = ref<any>([]);
  85. watch(
  86. () => props.modelValue,
  87. async (val) => {
  88. if (val) {
  89. let temp = 1;
  90. // 首先将值转为数组
  91. let list = [];
  92. if (props.format === 'array' && Array.isArray(val)) {
  93. list = val;
  94. } else if (props.format === 'object' || props.isObject) {
  95. list = [val];
  96. } else {
  97. const res = await listByIds(val as string);
  98. list = res.data.map((oss) => {
  99. const data = { name: oss.originalName, url: oss.url, ossId: oss.ossId };
  100. return data;
  101. });
  102. }
  103. // 然后将数组转为对象数组
  104. fileList.value = list.map((item) => {
  105. item = { name: item.fileName ? item.fileName : item.name, url: item.url, fileSize: item.fileSize, fileType: item.fileType };
  106. item.uid = item.uid || new Date().getTime() + temp++;
  107. return item;
  108. });
  109. } else {
  110. fileList.value = [];
  111. return [];
  112. }
  113. },
  114. { deep: true, immediate: true }
  115. );
  116. // 上传前校检格式和大小
  117. const handleBeforeUpload = (file: any) => {
  118. // 校检文件类型
  119. if (props.fileType.length) {
  120. loading.value = true;
  121. const fileName = file.name.split('.');
  122. const fileExt = fileName[fileName.length - 1];
  123. const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
  124. if (!isTypeOk) {
  125. proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}格式文件!`);
  126. loading.value = false;
  127. return false;
  128. }
  129. }
  130. // 校检文件大小
  131. if (props.fileSize) {
  132. const isLt = file.size / 1024 / 1024 < props.fileSize;
  133. if (!isLt) {
  134. loading.value = false;
  135. proxy?.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
  136. return false;
  137. }
  138. }
  139. number.value++;
  140. return true;
  141. };
  142. // 文件个数超出
  143. const handleExceed = () => {
  144. proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
  145. };
  146. // 上传失败
  147. const handleUploadError = () => {
  148. loading.value = false;
  149. proxy?.$modal.msgError('上传文件失败');
  150. };
  151. // 上传成功回调
  152. const handleUploadSuccess = (res: any, file: UploadFile) => {
  153. loading.value = false;
  154. if (res.code === 200) {
  155. uploadList.value.push({
  156. name: res.data.fileName,
  157. url: res.data.url,
  158. ossId: res.data.ossId,
  159. fileSize: file?.raw.size,
  160. fileType: file?.raw.type
  161. });
  162. uploadedSuccessfully();
  163. } else {
  164. number.value--;
  165. proxy?.$modal.msgError(res.msg);
  166. fileUploadRef.value?.handleRemove(file);
  167. uploadedSuccessfully();
  168. }
  169. };
  170. // 上传结束处理
  171. const uploadedSuccessfully = () => {
  172. if (number.value > 0 && uploadList.value.length === number.value) {
  173. fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);
  174. uploadList.value = [];
  175. number.value = 0;
  176. const valuef = fileList.value.map(({ name, url, fileType, fileSize, ossId }) => ({ fileName: name, url, fileSize, fileType, ossId }));
  177. if (props.format === 'id') {
  178. emit('change', listToString(valuef));
  179. emit('update:modelValue', listToString(valuef));
  180. } else if (props.isObject || props.format === 'object') {
  181. emit('change', valuef[0])
  182. emit('update:modelValue', valuef[0]);
  183. } else {
  184. emit('change', valuef)
  185. emit('update:modelValue', valuef);
  186. }
  187. }
  188. };
  189. const handleOnProgress = (event: any, file: any, list: any) => {
  190. const progress = Math.round((event.loaded / event.total) * 100);
  191. fileList.value = [...list];
  192. };
  193. // 删除文件
  194. const handleDelete = (index: number) => {
  195. fileUploadRef.value?.abort(fileList.value[index]);
  196. fileList.value.splice(index, 1);
  197. const valuef = fileList.value.map(({ name, url, fileType, fileSize }) => ({ fileName: name, url, fileSize, fileType }));
  198. if (props.isObject) {
  199. emit('change', null)
  200. emit('update:modelValue', null);
  201. } else {
  202. emit('change', valuef)
  203. emit('update:modelValue', valuef);
  204. }
  205. loading.value = false;
  206. };
  207. // 获取文件名称
  208. const getFileName = (name: string) => {
  209. // 如果是url那么取最后的名字 如果不是直接返回
  210. if (name.lastIndexOf('/') > -1) {
  211. return name.slice(name.lastIndexOf('/') + 1);
  212. } else {
  213. return name;
  214. }
  215. };
  216. // 对象转成指定字符串分隔
  217. const listToString = (list: any[], separator?: string) => {
  218. let strs = '';
  219. separator = separator || ',';
  220. list.forEach((item) => {
  221. if (item.ossId) {
  222. strs += item.ossId + separator;
  223. }
  224. });
  225. return strs != '' ? strs.substring(0, strs.length - 1) : '';
  226. };
  227. </script>
  228. <style scoped lang="scss">
  229. .btn-file {
  230. width: 90px;
  231. height: 40px;
  232. line-height: 40px;
  233. border-radius: 8px;
  234. color: #666;
  235. text-align: center;
  236. background-color: #f7f7f7;
  237. }
  238. .upload-list-img {
  239. background-color: #f7f7f7;
  240. border-radius: 8px;
  241. &.mt10 {
  242. margin-top: 10px;
  243. }
  244. }
  245. .right-item {
  246. padding: 10px 16px;
  247. cursor: pointer;
  248. &:hover {
  249. color: var(--el-color-primary);
  250. }
  251. }
  252. .delete-item {
  253. width: 40px;
  254. cursor: pointer;
  255. }
  256. .upload-file-list.white {
  257. .btn-file {
  258. background-color: #fff;
  259. }
  260. .upload-list-img {
  261. background-color: #fff;
  262. }
  263. }
  264. .right-wrap {
  265. padding: 6px 10px;
  266. box-sizing: border-box;
  267. }
  268. .progress {
  269. position: absolute;
  270. left: 0;
  271. bottom: 0;
  272. height: 1px;
  273. background-color: var(--el-color-primary);
  274. }
  275. </style>