image-upload.vue 2.3 KB

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