index.vue 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. <template>
  2. <div class="component-upload-image">
  3. <el-upload
  4. multiple
  5. :action="uploadImgUrl"
  6. :list-type="isPicCard?'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. :on-remove="handleDelete"
  14. :show-file-list="true"
  15. :headers="headers"
  16. :file-list="fileList"
  17. :on-preview="handlePictureCardPreview"
  18. :class="{hide: this.fileList.length >= this.limit}"
  19. >
  20. <i class="el-icon-plus"></i>
  21. </el-upload>
  22. <!-- 上传提示 -->
  23. <div class="el-upload__tip" slot="tip" v-if="showTip">
  24. 请上传
  25. <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
  26. <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
  27. 的文件
  28. </div>
  29. <el-dialog :close-on-click-modal="false"
  30. :visible.sync="dialogVisible"
  31. title="预览"
  32. width="800"
  33. append-to-body
  34. >
  35. <img
  36. :src="dialogImageUrl"
  37. style="display: block; max-width: 100%; margin: 0 auto"
  38. />
  39. </el-dialog>
  40. </div>
  41. </template>
  42. <script>
  43. import { getToken } from "@/utils/auth";
  44. export default {
  45. props: {
  46. value: [String, Object, Array],
  47. // 图片数量限制
  48. limit: {
  49. type: Number,
  50. default: 5,
  51. },
  52. // 大小限制(MB)
  53. fileSize: {
  54. type: Number,
  55. default: 5,
  56. },
  57. // 文件类型, 例如['png', 'jpg', 'jpeg']
  58. fileType: {
  59. type: Array,
  60. default: () => ["png", "jpg", "jpeg"],
  61. },
  62. // 是否显示提示
  63. isShowTip: {
  64. type: Boolean,
  65. default: true
  66. },
  67. // 是否显示图片框
  68. isPicCard: {
  69. type: Boolean,
  70. default: true
  71. },
  72. },
  73. data() {
  74. return {
  75. number: 0,
  76. uploadList: [],
  77. dialogImageUrl: "",
  78. dialogVisible: false,
  79. hideUpload: false,
  80. baseUrl: process.env.VUE_APP_BASE_API,
  81. uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
  82. headers: {
  83. Authorization: "Bearer " + getToken(),
  84. },
  85. fileList: []
  86. };
  87. },
  88. watch: {
  89. value: {
  90. handler(val) {
  91. if (val) {
  92. // 首先将值转为数组
  93. const list = Array.isArray(val) ? val : this.value.split(',');
  94. // 然后将数组转为对象数组
  95. this.fileList = list.map(item => {
  96. if (typeof item === "string") {
  97. if (item.indexOf(this.baseUrl) === -1) {
  98. item = { name: this.getFileName(item), url: this.baseUrl + item };
  99. } else {
  100. item = { name: this.getFileName(item), url: item };
  101. }
  102. }
  103. return item;
  104. });
  105. } else {
  106. this.fileList = [];
  107. return [];
  108. }
  109. },
  110. deep: true,
  111. immediate: true
  112. }
  113. },
  114. computed: {
  115. // 是否显示提示
  116. showTip() {
  117. return this.isShowTip && (this.fileType || this.fileSize);
  118. },
  119. },
  120. methods: {
  121. // 上传前loading加载
  122. handleBeforeUpload(file) {
  123. let isImg = false;
  124. if (this.fileType.length) {
  125. let fileExtension = "";
  126. if (file.name.lastIndexOf(".") > -1) {
  127. fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
  128. }
  129. isImg = this.fileType.some(type => {
  130. if (file.type.indexOf(type) > -1) return true;
  131. if (fileExtension && fileExtension.indexOf(type) > -1) return true;
  132. return false;
  133. });
  134. } else {
  135. isImg = file.type.indexOf("image") > -1;
  136. }
  137. if (!isImg) {
  138. this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
  139. return false;
  140. }
  141. if (this.fileSize) {
  142. const isLt = file.size / 1024 / 1024 < this.fileSize;
  143. if (!isLt) {
  144. this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
  145. return false;
  146. }
  147. }
  148. this.$modal.loading("正在上传图片,请稍候...");
  149. this.number++;
  150. },
  151. // 文件个数超出
  152. handleExceed() {
  153. this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
  154. },
  155. // 上传成功回调
  156. handleUploadSuccess(res, file) {
  157. if (res.code === 200) {
  158. this.uploadList.push({ name: res.fileName, url: res.fileName });
  159. this.uploadedSuccessfully();
  160. } else {
  161. this.number--;
  162. this.$modal.closeLoading();
  163. this.$modal.msgError(res.msg);
  164. this.$refs.imageUpload.handleRemove(file);
  165. this.uploadedSuccessfully();
  166. }
  167. },
  168. // 删除图片
  169. handleDelete(file) {
  170. const findex = this.fileList.map(f => f.name).indexOf(file.name);
  171. if (findex > -1) {
  172. this.fileList.splice(findex, 1);
  173. this.$emit("input", this.listToString(this.fileList));
  174. }
  175. },
  176. // 上传失败
  177. handleUploadError() {
  178. this.$modal.msgError("上传图片失败,请重试");
  179. this.$modal.closeLoading();
  180. },
  181. // 上传结束处理
  182. uploadedSuccessfully() {
  183. if (this.number > 0 && this.uploadList.length === this.number) {
  184. this.fileList = this.fileList.concat(this.uploadList);
  185. this.uploadList = [];
  186. this.number = 0;
  187. this.$emit("input", this.listToString(this.fileList));
  188. this.$modal.closeLoading();
  189. }
  190. },
  191. // 获取文件名称
  192. getFileName(name) {
  193. if (name.lastIndexOf("/") > -1) {
  194. const newName = name.slice(name.lastIndexOf("/") + 1)
  195. const names = newName.split(".")
  196. if ((names.size = 2) && (names[0].length > 19)) {
  197. return newName.substring(0, names[0].length - 19) + '.' + names[1]
  198. } else {
  199. return newName
  200. }
  201. } else {
  202. return "";
  203. }
  204. },
  205. // 预览
  206. handlePictureCardPreview(file) {
  207. this.dialogImageUrl = file.url;
  208. this.dialogVisible = true;
  209. },
  210. // 对象转成指定字符串分隔
  211. listToString(list, separator) {
  212. let strs = "";
  213. separator = separator || ",";
  214. for (let i in list) {
  215. if (list[i].url) {
  216. strs += list[i].url.replace(this.baseUrl, "") + separator;
  217. }
  218. }
  219. return strs != '' ? strs.substr(0, strs.length - 1) : '';
  220. }
  221. }
  222. };
  223. </script>
  224. <style scoped lang="scss">
  225. // .el-upload--picture-card 控制加号部分
  226. ::v-deep.hide .el-upload--picture-card {
  227. display: none;
  228. }
  229. // 去掉动画效果
  230. ::v-deep .el-list-enter-active,
  231. ::v-deep .el-list-leave-active {
  232. transition: all 0s;
  233. }
  234. ::v-deep .el-list-enter, .el-list-leave-active {
  235. opacity: 0;
  236. transform: translateY(0);
  237. }
  238. </style>