index.vue 5.6 KB

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