index.vue 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. <template>
  2. <div class="component-upload-image">
  3. <el-upload ref="imageUpload" multiple :action="uploadImgUrl" list-type="picture-card" :on-success="handleUploadSuccess" :before-upload="handleBeforeUpload" :limit="limit" :on-error="handleUploadError" :on-exceed="handleExceed" :before-remove="handleDelete" :show-file-list="true" :headers="headers" :file-list="fileList" :on-preview="handlePictureCardPreview" :class="{ hide: fileList.length >= limit }">
  4. <el-icon class="avatar-uploader-icon">
  5. <plus />
  6. </el-icon>
  7. </el-upload>
  8. <!-- 上传提示 -->
  9. <div v-if="showTip" class="el-upload__tip">
  10. 请上传
  11. <template v-if="fileSize">
  12. 大小不超过
  13. <b style="color: #f56c6c">{{ fileSize }}MB</b>
  14. </template>
  15. <template v-if="fileType">
  16. 格式为
  17. <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
  18. </template>
  19. 的文件
  20. </div>
  21. <el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body>
  22. <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
  23. </el-dialog>
  24. </div>
  25. </template>
  26. <script setup lang="ts">
  27. import { listByIds, delOss } from '@/api/system/oss';
  28. import { OssVO } from '@/api/system/oss/types';
  29. import { propTypes } from '@/utils/propTypes';
  30. import { globalHeaders } from '@/utils/request';
  31. import { compressAccurately } from 'image-conversion';
  32. const props = defineProps({
  33. modelValue: {
  34. type: [String, Object, Array],
  35. default: () => []
  36. },
  37. isString: propTypes.bool.def(false),
  38. // 图片数量限制
  39. limit: propTypes.number.def(5),
  40. // 大小限制(MB)
  41. fileSize: propTypes.number.def(5),
  42. // 文件类型, 例如['png', 'jpg', 'jpeg']
  43. fileType: propTypes.array.def(['png', 'jpg', 'jpeg']),
  44. // 是否显示提示
  45. isShowTip: {
  46. type: Boolean,
  47. default: true
  48. },
  49. // 是否支持压缩,默认否
  50. compressSupport: {
  51. type: Boolean,
  52. default: false
  53. },
  54. // 压缩目标大小,单位KB。默认300KB以上文件才压缩,并压缩至300KB以内
  55. compressTargetSize: propTypes.number.def(300)
  56. });
  57. const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  58. const emit = defineEmits(['update:modelValue']);
  59. const number = ref(0);
  60. const uploadList = ref<any[]>([]);
  61. const dialogImageUrl = ref('');
  62. const dialogVisible = ref(false);
  63. const baseUrl = import.meta.env.VITE_APP_BASE_API;
  64. const uploadImgUrl = ref(baseUrl + '/resource/oss/upload'); // 上传的图片服务器地址
  65. const headers = ref(globalHeaders());
  66. const fileList = ref<any[]>([]);
  67. const showTip = computed(() => props.isShowTip && (props.fileType || props.fileSize));
  68. const imageUploadRef = ref<ElUploadInstance>();
  69. watch(
  70. () => props.modelValue,
  71. async (val: string) => {
  72. if (val) {
  73. // 首先将值转为数组
  74. let list: any[] = [];
  75. if (Array.isArray(val)) {
  76. if (props.isString) {
  77. list = val.map((item) => {
  78. return {
  79. url: item
  80. };
  81. });
  82. } else {
  83. list = val as OssVO[];
  84. }
  85. } else if (val.startsWith('http')) {
  86. if (val.split(',').length > 0){
  87. val.split(',').forEach((item) => {
  88. list.push({ url: item });
  89. });
  90. }else {
  91. list = [{
  92. url: val
  93. }];
  94. }
  95. } else {
  96. const res = await listByIds(val);
  97. list = res.data;
  98. }
  99. // 然后将数组转为对象数组
  100. fileList.value = list.map((item) => {
  101. // 字符串回显处理 如果此处存的是url可直接回显 如果存的是id需要调用接口查出来
  102. let itemData;
  103. if (typeof item === 'string') {
  104. itemData = { name: item, url: item };
  105. } else {
  106. // 此处name使用ossId 防止删除出现重名
  107. itemData = { name: item.ossId, url: item.url, ossId: item.ossId };
  108. }
  109. return itemData;
  110. });
  111. } else {
  112. fileList.value = [];
  113. return [];
  114. }
  115. },
  116. { deep: true, immediate: true }
  117. );
  118. /** 上传前loading加载 */
  119. const handleBeforeUpload = (file: any) => {
  120. let isImg = false;
  121. if (props.fileType.length) {
  122. let fileExtension = '';
  123. if (file.name.lastIndexOf('.') > -1) {
  124. fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
  125. }
  126. isImg = props.fileType.some((type: any) => {
  127. if (file.type.indexOf(type) > -1) return true;
  128. if (fileExtension && fileExtension.indexOf(type) > -1) return true;
  129. return false;
  130. });
  131. } else {
  132. isImg = file.type.indexOf('image') > -1;
  133. }
  134. if (!isImg) {
  135. proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}图片格式文件!`);
  136. return false;
  137. }
  138. if (file.name.includes(',')) {
  139. proxy?.$modal.msgError('文件名不正确,不能包含英文逗号!');
  140. return false;
  141. }
  142. if (props.fileSize) {
  143. const isLt = file.size / 1024 / 1024 < props.fileSize;
  144. if (!isLt) {
  145. proxy?.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
  146. return false;
  147. }
  148. }
  149. //压缩图片,开启压缩并且大于指定的压缩大小时才压缩
  150. if (props.compressSupport && file.size / 1024 > props.compressTargetSize) {
  151. proxy?.$modal.loading('正在上传图片,请稍候...');
  152. number.value++;
  153. return compressAccurately(file, props.compressTargetSize);
  154. } else {
  155. proxy?.$modal.loading('正在上传图片,请稍候...');
  156. number.value++;
  157. }
  158. };
  159. // 文件个数超出
  160. const handleExceed = () => {
  161. proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
  162. };
  163. // 上传成功回调
  164. const handleUploadSuccess = (res: any, file: UploadFile) => {
  165. if (res.code === 200) {
  166. if (props.isString) {
  167. uploadList.value.push(res.data.url);
  168. } else {
  169. uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId });
  170. }
  171. uploadedSuccessfully();
  172. } else {
  173. number.value--;
  174. proxy?.$modal.closeLoading();
  175. proxy?.$modal.msgError(res.msg);
  176. imageUploadRef.value?.handleRemove(file);
  177. uploadedSuccessfully();
  178. }
  179. };
  180. // 删除图片
  181. const handleDelete = (file: UploadFile): boolean => {
  182. if (props.isString) {
  183. var findex = fileList.value.map((f) => f.url).indexOf(file.url);
  184. }else {
  185. var findex = fileList.value.map((f) => f.name).indexOf(file.name);
  186. }
  187. if (findex > -1 && uploadList.value.length === number.value) {
  188. let ossId = fileList.value[findex].ossId;
  189. if (!props.isString) {
  190. delOss(ossId);
  191. }
  192. fileList.value.splice(findex, 1);
  193. emit('update:modelValue', listToString(fileList.value));
  194. return false;
  195. }
  196. return true;
  197. };
  198. // 上传结束处理
  199. const uploadedSuccessfully = () => {
  200. if (number.value > 0 && uploadList.value.length === number.value) {
  201. if (props.isString) {
  202. uploadList.value.forEach((item) => {
  203. fileList.value.push({ url: item });
  204. });
  205. } else {
  206. fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value);
  207. }
  208. uploadList.value = [];
  209. number.value = 0;
  210. emit('update:modelValue', listToString(fileList.value));
  211. proxy?.$modal.closeLoading();
  212. }
  213. };
  214. // 上传失败
  215. const handleUploadError = () => {
  216. proxy?.$modal.msgError('上传图片失败');
  217. proxy?.$modal.closeLoading();
  218. };
  219. // 预览
  220. const handlePictureCardPreview = (file: any) => {
  221. dialogImageUrl.value = file.url;
  222. dialogVisible.value = true;
  223. };
  224. // 对象转成指定字符串分隔
  225. const listToString = (list: any[], separator?: string) => {
  226. let strs = '';
  227. separator = separator || ',';
  228. for (let i in list) {
  229. if (props.isString) {
  230. strs += list[i].url + separator;
  231. } else if (undefined !== list[i].ossId && list[i].url.indexOf('blob:') !== 0) {
  232. strs += list[i].ossId + separator;
  233. }
  234. }
  235. return strs != '' ? strs.substring(0, strs.length - 1) : '';
  236. };
  237. </script>
  238. <style scoped lang="scss">
  239. // .el-upload--picture-card 控制加号部分
  240. :deep(.hide .el-upload--picture-card) {
  241. display: none;
  242. }
  243. </style>