index.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <template>
  2. <ximgresiz @upload="doUpload" :avatarSrc="value" quality="1" ref="avatar" />
  3. </template>
  4. <script>
  5. import {
  6. ossInfo
  7. } from '@/api/oss.js'
  8. import {
  9. getRandomNum
  10. } from '@/utils/common.js'
  11. import imgUpload from '@/utils/upload.js'
  12. import ximgresiz from '@/components/xy-imgResiz/index.vue'
  13. export default {
  14. components: {
  15. ximgresiz
  16. },
  17. data() {
  18. return {
  19. uploadData: { //oss返回数据
  20. policy: undefined,
  21. Signature: undefined,
  22. OSSAccessKeyId: undefined,
  23. uploadImgUrl: undefined,
  24. dir: undefined,
  25. key: undefined
  26. },
  27. }
  28. },
  29. props: {
  30. value: {
  31. type: String,
  32. default () {
  33. return ''
  34. }
  35. },
  36. },
  37. methods: {
  38. fChooseImg(obj) {
  39. this.$refs.avatar.fChooseImg(obj);
  40. },
  41. oss() {
  42. return new Promise((resolve, reject) => {
  43. ossInfo().then(response => {
  44. this.uploadData.policy = response.data.policy;
  45. this.uploadData.Signature = response.data.signature;
  46. this.uploadData.OSSAccessKeyId = response.data.accessid;
  47. this.uploadData.uploadImgUrl = response.data.domain;
  48. this.uploadData.dir = response.data.dir;
  49. resolve(response)
  50. }).catch(err => {
  51. reject(err)
  52. })
  53. })
  54. },
  55. async doUpload(rsp) {
  56. await this.oss() //获取oss数据
  57. await this.uploadFilePromise(rsp.path).then(res => {
  58. this.$emit('success', res)
  59. })
  60. },
  61. uploadFilePromise(url) {
  62. //组装上传数据
  63. let timestamp = new Date().getTime()
  64. let randomNum = getRandomNum(10000, 99999)
  65. let imgType = url.substr(url.indexOf('.'))
  66. this.uploadData.key = `${this.uploadData.dir}${timestamp}${randomNum}${imgType}`
  67. let params = {
  68. policy: this.uploadData.policy,
  69. Signature: this.uploadData.Signature,
  70. OSSAccessKeyId: this.uploadData.OSSAccessKeyId,
  71. key: this.uploadData.key
  72. }
  73. return new Promise((resolve, reject) => {
  74. imgUpload({
  75. url: this.uploadData.uploadImgUrl,
  76. header: {
  77. isToken: true
  78. },
  79. formData: params,
  80. filePath: url
  81. }).then((res) => {
  82. console.log('res', res)
  83. let url = this.uploadData.uploadImgUrl + '/' + this.uploadData
  84. .key //图片路径需要前端组装
  85. resolve(url)
  86. }).catch(err => {
  87. reject(err)
  88. })
  89. })
  90. },
  91. }
  92. }
  93. </script>