Upload.vue 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <template>
  2. <div class="upload">
  3. <el-upload
  4. class="avatar-uploader"
  5. action="https://jsonplaceholder.typicode.com/posts/"
  6. :show-file-list="false"
  7. :on-success="handleAvatarSuccess"
  8. :before-upload="beforeAvatarUpload">
  9. <img v-if="imageUrl" :src="imageUrl" class="avatar">
  10. <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  11. </el-upload>
  12. </div>
  13. </template>
  14. <script>
  15. export default {
  16. data() {
  17. return {
  18. imageUrl: ''
  19. };
  20. },
  21. methods: {
  22. handleAvatarSuccess(res, file) {
  23. this.imageUrl = URL.createObjectURL(file.raw);
  24. },
  25. beforeAvatarUpload(file) {
  26. const isJPG = file.type === 'image/jpeg';
  27. const isLt2M = file.size / 1024 / 1024 < 2;
  28. if (!isJPG) {
  29. this.$message.error('上传头像图片只能是 JPG 格式!');
  30. }
  31. if (!isLt2M) {
  32. this.$message.error('上传头像图片大小不能超过 2MB!');
  33. }
  34. return isJPG && isLt2M;
  35. }
  36. }
  37. }
  38. </script>
  39. <style scoped>
  40. .avatar-uploader .el-upload {
  41. border: 1px dashed #d9d9d9;
  42. border-radius: 6px;
  43. cursor: pointer;
  44. position: relative;
  45. overflow: hidden;
  46. }
  47. .avatar-uploader .el-upload:hover {
  48. border-color: #409EFF;
  49. }
  50. .avatar-uploader-icon {
  51. font-size: 28px;
  52. color: #8c939d;
  53. width: 178px;
  54. height: 178px;
  55. line-height: 178px;
  56. text-align: center;
  57. }
  58. .avatar {
  59. width: 178px;
  60. height: 178px;
  61. display: block;
  62. }
  63. </style>