index.vue 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. <template>
  2. <div class="component-upload-image">
  3. <el-upload
  4. :action="uploadImgUrl"
  5. :headers="headers"
  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. name="file"
  13. :on-remove="handleRemove"
  14. :show-file-list="true"
  15. :file-list="fileList"
  16. :on-preview="handlePictureCardPreview"
  17. :class="{hide: this.fileList.length >= this.limit}"
  18. >
  19. <i class="el-icon-plus"></i>
  20. </el-upload>
  21. <!-- 上传提示 -->
  22. <!-- <div class="el-upload__tip" slot="tip" v-if="showTip">
  23. 请上传
  24. <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
  25. <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
  26. 的文件
  27. </div> -->
  28. <el-dialog
  29. :visible.sync="dialogVisible"
  30. title="预览"
  31. width="800"
  32. append-to-body
  33. >
  34. <img
  35. :src="dialogImageUrl"
  36. style="display: block; max-width: 100%; margin: 0 auto"
  37. />
  38. </el-dialog>
  39. </div>
  40. </template>
  41. <script>
  42. import { getToken } from "@/utils/auth";
  43. import { Loading } from 'element-ui';
  44. export default {
  45. props: {
  46. value: [String, Object, Array],
  47. // 图片数量限制
  48. limit: {
  49. type: Number,
  50. default: 10,
  51. },
  52. // 大小限制(MB)
  53. fileSize: {
  54. type: Number,
  55. default: 500,
  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. data() {
  69. return {
  70. finalQuality:1,
  71. dialogImageUrl: "",
  72. dialogVisible: false,
  73. hideUpload: false,
  74. baseUrl: process.env.VUE_APP_BASE_API,
  75. uploadImgUrl: process.env.VUE_APP_BASE_API+"/common/uploadOSS", // 上传的图片服务器地址
  76. headers: {
  77. Authorization: "Bearer " + getToken(),
  78. },
  79. fileList: []
  80. };
  81. },
  82. watch: {
  83. value: {
  84. handler(val) {
  85. if (val) {
  86. // 首先将值转为数组
  87. const list = Array.isArray(val) ? val : this.value.split(',');
  88. // 然后将数组转为对象数组
  89. this.fileList = list.map(item => {
  90. if (typeof item === "string") {
  91. if (item.indexOf(this.baseUrl) === -1) {
  92. item = { name: item, url: item };
  93. } else {
  94. item = { name: item, url: item };
  95. }
  96. }
  97. return item;
  98. });
  99. } else {
  100. this.fileList = [];
  101. return [];
  102. }
  103. },
  104. deep: true,
  105. immediate: true
  106. }
  107. },
  108. computed: {
  109. // 是否显示提示
  110. showTip() {
  111. return this.isShowTip && (this.fileType || this.fileSize);
  112. },
  113. },
  114. methods: {
  115. // 删除图片
  116. handleRemove(file, fileList) {
  117. const findex = this.fileList.map(f => f.name).indexOf(file.name);
  118. if(findex > -1) {
  119. this.fileList.splice(findex, 1);
  120. this.$emit("input", this.listToString(this.fileList));
  121. }
  122. },
  123. // 上传成功回调
  124. handleUploadSuccess(res) {
  125. if (!res || res.code === 401 || !res.url) {
  126. this.$message.error((res && res.msg) || "上传失败,请重新登录后重试");
  127. if (this.loading) {
  128. this.loading.close();
  129. }
  130. return;
  131. }
  132. this.fileList.push({ name: res.url, url: res.url });
  133. this.$emit("input", this.listToString(this.fileList));
  134. this.loading.close();
  135. },
  136. // 上传前loading加载
  137. handleBeforeUpload(file) {
  138. this.headers.Authorization = "Bearer " + getToken();
  139. let isImg = false;
  140. if (this.fileType.length) {
  141. let fileExtension = "";
  142. if (file.name.lastIndexOf(".") > -1) {
  143. fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
  144. }
  145. isImg = this.fileType.some(type => {
  146. if (file.type.indexOf(type) > -1) return true;
  147. if (fileExtension && fileExtension.indexOf(type) > -1) return true;
  148. return false;
  149. });
  150. } else {
  151. isImg = file.type.indexOf("image") > -1;
  152. }
  153. if (!isImg) {
  154. this.$message.error(
  155. `文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`
  156. );
  157. return false;
  158. }
  159. return new Promise((resolve, reject) => {
  160. if (file.size / 1024 / 1024 > 3) {
  161. this.$message.error('上传的图片不能超过3MB');
  162. reject();
  163. return;
  164. }
  165. if (file.size / 1024 / 1024 > 1) {
  166. const loadingInstance = Loading.service({ text: '图片内存过大正在压缩图片...' });
  167. // 文件大于1MB时进行压缩
  168. this.compressImage(file).then((compressedFile) => {
  169. loadingInstance.close();
  170. if (compressedFile.size / 1024 > 1000) {
  171. this.$message.error('图片压缩后仍大于1000KB');
  172. reject();
  173. } else {
  174. // this.$message.success(`图片压缩成功,最终质量为: ${this.finalQuality.toFixed(2)}`);
  175. console.log(`图片压缩成功,最终质量为: ${this.finalQuality.toFixed(2)}`);
  176. console.log(`最终内存大小为: ${(compressedFile.size/1024).toFixed(2)}KB`);
  177. resolve(compressedFile);
  178. }
  179. }).catch((err) => {
  180. loadingInstance.close();
  181. console.error(err);
  182. reject();
  183. });
  184. } else {
  185. resolve(file);
  186. }
  187. this.loading = this.$loading({
  188. lock: true,
  189. text: "上传中",
  190. background: "rgba(0, 0, 0, 0.7)",
  191. });
  192. });
  193. // if (this.fileSize) {
  194. // const isLt = file.size / 1024 < this.fileSize;
  195. // if (!isLt) {
  196. // this.$message.error(`上传头像图片大小不能超过 ${this.fileSize} KB!`);
  197. // return false;
  198. // }
  199. // }
  200. },
  201. compressImage(file) {
  202. return new Promise((resolve, reject) => {
  203. const reader = new FileReader();
  204. reader.readAsDataURL(file);
  205. reader.onload = (event) => {
  206. const img = new Image();
  207. img.src = event.target.result;
  208. img.onload = () => {
  209. const canvas = document.createElement('canvas');
  210. const ctx = canvas.getContext('2d');
  211. const width = img.width;
  212. const height = img.height;
  213. canvas.width = width;
  214. canvas.height = height;
  215. ctx.drawImage(img, 0, 0, width, height);
  216. let quality = 1; // 初始压缩质量
  217. let dataURL = canvas.toDataURL('image/jpeg', quality);
  218. // 逐步压缩,直到图片大小小于500KB并且压缩质量不再降低
  219. while (dataURL.length / 1024 > 500 && quality > 0.1) {
  220. quality -= 0.01;
  221. dataURL = canvas.toDataURL('image/jpeg', quality);
  222. }
  223. this.finalQuality = quality; // 存储最终的压缩质量
  224. if (dataURL.length / 1024 > 1000) {
  225. reject(new Error('压缩后图片仍然大于1000KB'));
  226. return;
  227. }
  228. const arr = dataURL.split(',');
  229. const mime = arr[0].match(/:(.*?);/)[1];
  230. const bstr = atob(arr[1]);
  231. let n = bstr.length;
  232. const u8arr = new Uint8Array(n);
  233. while (n--) {
  234. u8arr[n] = bstr.charCodeAt(n);
  235. }
  236. const compressedFile = new Blob([u8arr], { type: mime });
  237. compressedFile.name = file.name;
  238. resolve(compressedFile);
  239. };
  240. img.onerror = (error) => {
  241. reject(error);
  242. };
  243. };
  244. reader.onerror = (error) => {
  245. reject(error);
  246. };
  247. });
  248. },
  249. // 文件个数超出
  250. handleExceed() {
  251. this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
  252. },
  253. // 上传失败
  254. handleUploadError() {
  255. this.$message({
  256. type: "error",
  257. message: "上传失败",
  258. });
  259. this.loading.close();
  260. },
  261. // 预览
  262. handlePictureCardPreview(file) {
  263. console.log(file)
  264. this.dialogImageUrl = file.url;
  265. this.dialogVisible = true;
  266. },
  267. // 对象转成指定字符串分隔
  268. listToString(list, separator) {
  269. let strs = "";
  270. separator = separator || ",";
  271. for (let i in list) {
  272. const url = list[i] && list[i].url;
  273. if (!url) {
  274. continue;
  275. }
  276. strs += String(url).replace(this.baseUrl, "") + separator;
  277. }
  278. return strs != '' ? strs.substr(0, strs.length - 1) : '';
  279. }
  280. }
  281. };
  282. </script>
  283. <style scoped lang="scss">
  284. // .el-upload--picture-card 控制加号部分
  285. ::v-deep.hide .el-upload--picture-card {
  286. display: none;
  287. }
  288. // 去掉动画效果
  289. ::v-deep .el-list-enter-active,
  290. ::v-deep .el-list-leave-active {
  291. transition: all 0s;
  292. }
  293. ::v-deep .el-list-enter, .el-list-leave-active {
  294. opacity: 0;
  295. transform: translateY(0);
  296. }
  297. </style>