file-upload.vue 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <template>
  2. <view @click="selectAndUpload()">
  3. <slot></slot>
  4. </view>
  5. </template>
  6. <script>
  7. import UNI_APP from '@/.env.js';
  8. export default {
  9. name: "file-upload",
  10. data() {
  11. return {
  12. uploadHeaders: {
  13. "accessToken": uni.getStorageSync('loginInfo').accessToken
  14. }
  15. }
  16. },
  17. props: {
  18. maxSize: {
  19. type: Number,
  20. default: 10*1024*1024
  21. },
  22. onBefore: {
  23. type: Function,
  24. default: null
  25. },
  26. onSuccess: {
  27. type: Function,
  28. default: null
  29. },
  30. onError: {
  31. type: Function,
  32. default: null
  33. }
  34. },
  35. methods: {
  36. selectAndUpload() {
  37. console.log(uni.chooseFile)
  38. console.log(uni.chooseMessageFile)
  39. let chooseFile = uni.chooseFile || uni.chooseMessageFile;
  40. chooseFile({
  41. success: (res) => {
  42. res.tempFiles.forEach((file) => {
  43. // 校验大小
  44. if (this.maxSize && file.size > this.maxSize) {
  45. this.$message.error(`文件大小不能超过 ${this.fileSizeStr}!`);
  46. this.$emit("fail", file);
  47. return;
  48. }
  49. if (!this.onBefore || this.onBefore(file)) {
  50. // 调用上传图片的接口
  51. this.uploadFile(file);
  52. }
  53. })
  54. }
  55. })
  56. },
  57. uploadFile(file) {
  58. uni.uploadFile({
  59. url: UNI_APP.BASE_URL + '/file/upload',
  60. header: {
  61. accessToken: uni.getStorageSync("loginInfo").accessToken
  62. },
  63. filePath: file.path, // 要上传文件资源的路径
  64. name: 'file',
  65. success: (res) => {
  66. let data = JSON.parse(res.data);
  67. if(data.code != 200){
  68. this.onError && this.onError(file, data);
  69. }else{
  70. this.onSuccess && this.onSuccess(file, data);
  71. }
  72. },
  73. fail: (err) => {
  74. this.onError && this.onError(file, err);
  75. }
  76. })
  77. }
  78. },
  79. computed: {
  80. fileSizeStr() {
  81. if (this.maxSize > 1024 * 1024) {
  82. return Math.round(this.maxSize / 1024 / 1024) + "M";
  83. }
  84. if (this.maxSize > 1024) {
  85. return Math.round(this.maxSize / 1024) + "KB";
  86. }
  87. return this.maxSize + "B";
  88. }
  89. }
  90. }
  91. </script>
  92. <style>
  93. </style>