utils.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import config from './config'
  2. export default {
  3. isHttp(path) {
  4. return path.startsWith('http') || path.startsWith('https')
  5. },
  6. upload(data) {
  7. return uni.uploadFile({
  8. url: this.isHttp(data.url) ? data.url : config.apiBaseUrl + data.url,
  9. name: data.name || 'file',
  10. formData: {
  11. ...data.formData,
  12. token: uni.getStorageSync('token')
  13. },
  14. header: data.header || {},
  15. filePath: data.filePath
  16. }).then(res => {
  17. return JSON.parse(res)
  18. })
  19. },
  20. uploadCloud(data) {
  21. return uniCloud.uploadFile(data).then(res => {
  22. return res
  23. })
  24. },
  25. chooseAndUpload(methods, chooseParam, uploadParam, isCloud) {
  26. const uploadArr = []
  27. return this[methods](chooseParam).then(file => {
  28. file.filePaths.forEach((filePath, index) => {
  29. if (isCloud) {
  30. uploadArr.push(this.uploadCloud({
  31. filePath,
  32. cloudPath: file.tempFiles[index].name,
  33. fileType: file.tempFiles[index].type
  34. }).then(res => {
  35. if (res.success) {
  36. return {
  37. filePath: res.fileID
  38. }
  39. } else {
  40. uni.showToast({
  41. title: res.msg,
  42. icon: 'none'
  43. })
  44. }
  45. }))
  46. } else{
  47. uploadArr.push(this.upload({
  48. ...uploadParam,
  49. filePath
  50. }).then(res => {
  51. if (res.code === 200 || res.success) {
  52. return res.data
  53. } else {
  54. uni.showToast({
  55. title: res.msg,
  56. icon: 'none'
  57. })
  58. }
  59. }))
  60. }
  61. })
  62. uni.showLoading({
  63. title: '上传中...'
  64. })
  65. return Promise.all(uploadArr).then(res => {
  66. uni.hideLoading()
  67. return res.filter(item => item)
  68. })
  69. })
  70. },
  71. chooseImage(data) {
  72. return uni.chooseImage({
  73. count: 1,
  74. ...data
  75. }).then(res => {
  76. console.log(res);
  77. return {
  78. filePaths: res.tempFilePaths,
  79. tempFiles: res.tempFiles
  80. }
  81. })
  82. },
  83. chooseAndUploadImage(chooseParam, uploadParam, isCloud) {
  84. return this.chooseAndUpload('chooseImage',chooseParam, uploadParam, isCloud)
  85. },
  86. chooseVideo(data) {
  87. return uni.chooseVideo({
  88. ...data
  89. }).then(res => {
  90. return {
  91. filePaths: [res.tempFilePath],
  92. tempFiles: [res.tempFile]
  93. }
  94. })
  95. },
  96. chooseAndUploadVideo(chooseParam, uploadParam, isCloud) {
  97. return this.chooseAndUpload('chooseVideo',chooseParam, uploadParam, isCloud)
  98. },
  99. }