image-upload.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <template>
  2. <view @click="selectAndUpload()">
  3. <slot></slot>
  4. </view>
  5. </template>
  6. <script>
  7. export default {
  8. name: "image-upload",
  9. data() {
  10. return {
  11. uploadHeaders: {
  12. "accessToken": uni.getStorageSync('loginInfo').accessToken
  13. }
  14. }
  15. },
  16. props: {
  17. maxCount:{
  18. type: Number,
  19. default: 1
  20. },
  21. maxSize: {
  22. type: Number,
  23. default: 5*1024*1024
  24. },
  25. sourceType:{
  26. type: String,
  27. default: 'album'
  28. },
  29. onBefore: {
  30. type: Function,
  31. default: null
  32. },
  33. onSuccess: {
  34. type: Function,
  35. default: null
  36. },
  37. onError: {
  38. type: Function,
  39. default: null
  40. }
  41. },
  42. methods: {
  43. selectAndUpload() {
  44. uni.chooseImage({
  45. count: this.maxCount, //最多可以选择的图片张数,默认9
  46. sourceType: [this.sourceType], //album 从相册选图,camera 使用相机,默认二者都有。如需直接开相机或直接选相册,请只使用一个选项
  47. sizeType: ['original'], //original 原图,compressed 压缩图,默认二者都有
  48. success: (res) => {
  49. res.tempFiles.forEach((file) => {
  50. // 校验大小
  51. if (this.maxSize && file.size > this.maxSize) {
  52. this.$message.error(`文件大小不能超过 ${this.fileSizeStr}!`);
  53. this.$emit("fail", file);
  54. return;
  55. }
  56. if (!this.onBefore || this.onBefore(file)) {
  57. // 调用上传图片的接口
  58. this.uploadImage(file);
  59. }
  60. })
  61. }
  62. })
  63. },
  64. uploadImage(file) {
  65. uni.uploadFile({
  66. url: process.env.BASE_URL + '/image/upload',
  67. header: {
  68. accessToken: uni.getStorageSync("loginInfo").accessToken
  69. },
  70. filePath: file.path, // 要上传文件资源的路径
  71. name: 'file',
  72. success: (res) => {
  73. let data = JSON.parse(res.data);
  74. if(data.code != 200){
  75. this.onError && this.onError(file, data);
  76. }else{
  77. this.onSuccess && this.onSuccess(file, data);
  78. }
  79. },
  80. fail: (err) => {
  81. console.log(err);
  82. this.onError && this.onError(file, err);
  83. }
  84. })
  85. }
  86. },
  87. computed: {
  88. fileSizeStr() {
  89. if (this.maxSize > 1024 * 1024) {
  90. return Math.round(this.maxSize / 1024 / 1024) + "M";
  91. }
  92. if (this.maxSize > 1024) {
  93. return Math.round(this.maxSize / 1024) + "KB";
  94. }
  95. return this.maxSize + "B";
  96. }
  97. }
  98. }
  99. </script>
  100. <style>
  101. </style>