多媒体信息发布平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
2.7 KiB

3 years ago
  1. <template>
  2. <!-- upload -->
  3. <div class="upload">
  4. <el-upload
  5. class="avatar-uploader"
  6. :action="domain"
  7. :http-request="upqiniu"
  8. :show-file-list="false"
  9. :before-upload="beforeUpload"
  10. >
  11. <img v-if="imageUrl" :src="imageUrl" class="avatar" />
  12. <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  13. </el-upload>
  14. </div>
  15. </template>
  16. <script>
  17. import axios from 'axios'
  18. import { getQiniuToken } from '@/api/material/material'
  19. export default {
  20. data() {
  21. return {
  22. imageUrl: '',
  23. token: {},
  24. // 七牛云的上传地址,根据自己所在地区选择,我这里是华南区
  25. domain: 'https://upload.qiniup.com/',
  26. // 这是七牛云空间的外链默认域名
  27. qiniuaddr: 'qiniu.aiyxlib.com'
  28. }
  29. },
  30. methods: {
  31. // 上传文件到七牛云
  32. upqiniu(req) {
  33. console.log(req)
  34. const config = {
  35. headers: { 'Content-Type': 'multipart/form-data' }
  36. }
  37. let filetype = ''
  38. if (req.file.type === 'image/png') {
  39. filetype = 'png'
  40. } else {
  41. filetype = 'jpg'
  42. }
  43. // 重命名要上传的文件
  44. const keyname = 'material' + Math.random() * 100 + '.' + filetype
  45. // 从后端获取上传凭证token
  46. getQiniuToken().then(res => {
  47. console.log(res)
  48. const formdata = new FormData()
  49. formdata.append('file', req.file)
  50. formdata.append('token', res.data)
  51. formdata.append('key', keyname)
  52. // 获取到凭证之后再将文件上传到七牛云空间
  53. axios.post(this.domain, formdata, config).then(res => {
  54. this.imageUrl = 'http://' + this.qiniuaddr + '/' + res.data.key
  55. console.log(this.imageUrl)
  56. })
  57. })
  58. // this.axios.get('/up/token').then(res => {
  59. // })
  60. },
  61. // 验证文件合法性
  62. beforeUpload(file) {
  63. const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  64. const isLt2M = file.size / 1024 / 1024 < 10
  65. if (!isJPG) {
  66. this.$message.error('上传头像图片只能是 JPG 格式!')
  67. }
  68. if (!isLt2M) {
  69. this.$message.error('上传头像图片大小不能超过 10MB!')
  70. }
  71. return isJPG && isLt2M
  72. }
  73. }
  74. }
  75. </script>
  76. <style scoped>
  77. .upload {
  78. width: 600px;
  79. margin: 0 auto;
  80. }
  81. .avatar-uploader .el-upload {
  82. border: 5px dashed #ca1717 !important;
  83. border-radius: 6px;
  84. cursor: pointer;
  85. position: relative;
  86. overflow: hidden;
  87. }
  88. .avatar-uploader .el-upload:hover {
  89. border-color: #409EFF;
  90. }
  91. .avatar-uploader-icon {
  92. font-size: 28px;
  93. color: #8c939d;
  94. width: 178px;
  95. height: 178px;
  96. line-height: 178px;
  97. text-align: center;
  98. }
  99. .avatar {
  100. width: 178px;
  101. height: 178px;
  102. display: block;
  103. }
  104. </style>