index.vue 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. <template>
  2. <div class="component-upload-image">
  3. <el-upload
  4. multiple
  5. :action="uploadImgUrl"
  6. list-type="picture-card"
  7. :on-success="handleUploadSuccess"
  8. :before-upload="handleBeforeUpload"
  9. :limit="limit"
  10. :on-error="handleUploadError"
  11. :on-exceed="handleExceed"
  12. ref="imageUpload"
  13. :before-remove="handleDelete"
  14. :show-file-list="true"
  15. :headers="headers"
  16. :file-list="fileList"
  17. :on-preview="handlePictureCardPreview"
  18. :class="{ hide: fileList.length >= limit }"
  19. >
  20. <el-icon class="avatar-uploader-icon"><plus /></el-icon>
  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. <el-dialog
  34. v-model="dialogVisible"
  35. title="预览"
  36. width="800px"
  37. append-to-body
  38. >
  39. <img
  40. :src="dialogImageUrl"
  41. style="display: block; max-width: 100%; margin: 0 auto"
  42. />
  43. </el-dialog>
  44. </div>
  45. </template>
  46. <script setup>
  47. import { getToken } from "@/utils/auth";
  48. import { isExternal } from "@/utils/validate";
  49. const props = defineProps({
  50. modelValue: [String, Object, Array],
  51. // 图片数量限制
  52. limit: {
  53. type: Number,
  54. default: 5,
  55. },
  56. // 大小限制(MB)
  57. fileSize: {
  58. type: Number,
  59. default: 5,
  60. },
  61. // 文件类型, 例如['png', 'jpg', 'jpeg']
  62. fileType: {
  63. type: Array,
  64. default: () => ["png", "jpg", "jpeg"],
  65. },
  66. // 是否显示提示
  67. isShowTip: {
  68. type: Boolean,
  69. default: true
  70. },
  71. });
  72. const { proxy } = getCurrentInstance();
  73. const emit = defineEmits();
  74. const number = ref(0);
  75. const uploadList = ref([]);
  76. const dialogImageUrl = ref("");
  77. const dialogVisible = ref(false);
  78. const baseUrl = import.meta.env.VITE_APP_BASE_API;
  79. const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传的图片服务器地址
  80. const headers = ref({ Authorization: "Bearer " + getToken() });
  81. const fileList = ref([]);
  82. const showTip = computed(
  83. () => props.isShowTip && (props.fileType || props.fileSize)
  84. );
  85. watch(() => props.modelValue, val => {
  86. if (val) {
  87. // 首先将值转为数组
  88. const list = Array.isArray(val) ? val : props.modelValue.split(",");
  89. // 然后将数组转为对象数组
  90. fileList.value = list.map(item => {
  91. if (typeof item === "string") {
  92. if (item.indexOf(baseUrl) === -1 && !isExternal(item)) {
  93. item = { name: baseUrl + item, url: baseUrl + item };
  94. } else {
  95. item = { name: item, url: item };
  96. }
  97. }
  98. return item;
  99. });
  100. } else {
  101. fileList.value = [];
  102. return [];
  103. }
  104. },{ deep: true, immediate: true });
  105. // 上传前loading加载
  106. function handleBeforeUpload(file) {
  107. let isImg = false;
  108. if (props.fileType.length) {
  109. let fileExtension = "";
  110. if (file.name.lastIndexOf(".") > -1) {
  111. fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
  112. }
  113. isImg = props.fileType.some(type => {
  114. if (file.type.indexOf(type) > -1) return true;
  115. if (fileExtension && fileExtension.indexOf(type) > -1) return true;
  116. return false;
  117. });
  118. } else {
  119. isImg = file.type.indexOf("image") > -1;
  120. }
  121. if (!isImg) {
  122. proxy.$modal.msgError(
  123. `文件格式不正确, 请上传${props.fileType.join("/")}图片格式文件!`
  124. );
  125. return false;
  126. }
  127. if (props.fileSize) {
  128. const isLt = file.size / 1024 / 1024 < props.fileSize;
  129. if (!isLt) {
  130. proxy.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
  131. return false;
  132. }
  133. }
  134. proxy.$modal.loading("正在上传图片,请稍候...");
  135. number.value++;
  136. }
  137. // 文件个数超出
  138. function handleExceed() {
  139. proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
  140. }
  141. // 上传成功回调
  142. function handleUploadSuccess(res, file) {
  143. if (res.code === 200) {
  144. uploadList.value.push({ name: res.fileName, url: res.fileName });
  145. uploadedSuccessfully();
  146. } else {
  147. number.value--;
  148. proxy.$modal.closeLoading();
  149. proxy.$modal.msgError(res.msg);
  150. proxy.$refs.imageUpload.handleRemove(file);
  151. uploadedSuccessfully();
  152. }
  153. }
  154. // 删除图片
  155. function handleDelete(file) {
  156. const findex = fileList.value.map(f => f.name).indexOf(file.name);
  157. if (findex > -1 && uploadList.value.length === number.value) {
  158. fileList.value.splice(findex, 1);
  159. emit("update:modelValue", listToString(fileList.value));
  160. return false;
  161. }
  162. }
  163. // 上传结束处理
  164. function uploadedSuccessfully() {
  165. if (number.value > 0 && uploadList.value.length === number.value) {
  166. fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
  167. uploadList.value = [];
  168. number.value = 0;
  169. emit("update:modelValue", listToString(fileList.value));
  170. proxy.$modal.closeLoading();
  171. }
  172. }
  173. // 上传失败
  174. function handleUploadError() {
  175. proxy.$modal.msgError("上传图片失败");
  176. proxy.$modal.closeLoading();
  177. }
  178. // 预览
  179. function handlePictureCardPreview(file) {
  180. dialogImageUrl.value = file.url;
  181. dialogVisible.value = true;
  182. }
  183. // 对象转成指定字符串分隔
  184. function listToString(list, separator) {
  185. let strs = "";
  186. separator = separator || ",";
  187. for (let i in list) {
  188. if (undefined !== list[i].url && list[i].url.indexOf("blob:") !== 0) {
  189. strs += list[i].url.replace(baseUrl, "") + separator;
  190. }
  191. }
  192. return strs != "" ? strs.substr(0, strs.length - 1) : "";
  193. }
  194. </script>
  195. <style scoped lang="scss">
  196. // .el-upload--picture-card 控制加号部分
  197. :deep(.hide .el-upload--picture-card) {
  198. display: none;
  199. }
  200. </style>