file-upload.vue 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <template>
  2. <view @click="selectAndUpload()">
  3. <slot></slot>
  4. </view>
  5. </template>
  6. <script>
  7. export default {
  8. name: "file-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: 10*1024*1024
  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. let chooseFile = uni.chooseFile || uni.chooseMessageFile;
  37. console.log(chooseFile)
  38. chooseFile({
  39. success: (res) => {
  40. res.tempFiles.forEach((file) => {
  41. // 校验大小
  42. if (this.maxSize && file.size > this.maxSize) {
  43. this.$message.error(`文件大小不能超过 ${this.fileSizeStr}!`);
  44. this.$emit("fail", file);
  45. return;
  46. }
  47. if (!this.onBefore || this.onBefore(file)) {
  48. // 调用上传图片的接口
  49. this.uploadFile(file);
  50. }
  51. })
  52. }
  53. })
  54. },
  55. uploadFile(file) {
  56. uni.uploadFile({
  57. url: process.env.BASE_URL + '/file/upload',
  58. header: {
  59. accessToken: uni.getStorageSync("loginInfo").accessToken
  60. },
  61. filePath: file.path, // 要上传文件资源的路径
  62. name: 'file',
  63. success: (res) => {
  64. let data = JSON.parse(res.data);
  65. if(data.code != 200){
  66. this.onError && this.onError(file, data);
  67. }else{
  68. this.onSuccess && this.onSuccess(file, data);
  69. }
  70. },
  71. fail: (err) => {
  72. this.onError && this.onError(file, err);
  73. }
  74. })
  75. }
  76. },
  77. computed: {
  78. fileSizeStr() {
  79. if (this.maxSize > 1024 * 1024) {
  80. return Math.round(this.maxSize / 1024 / 1024) + "M";
  81. }
  82. if (this.maxSize > 1024) {
  83. return Math.round(this.maxSize / 1024) + "KB";
  84. }
  85. return this.maxSize + "B";
  86. }
  87. }
  88. }
  89. </script>
  90. <style>
  91. </style>