uploadFile.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /**
  2. * 上传文件公共方法
  3. */
  4. import uniAsync from '@/utils/uni-async.js'// uni api async 化
  5. import {baseUrl} from './config.js'
  6. import store from '@/store/index.js'
  7. /**
  8. * 上传图片
  9. * count 同时上传张数
  10. */
  11. export const uploadImg=async (count)=>{
  12. const {tempFilePaths}=await uniAsync.chooseImage({count})
  13. uni.showLoading({
  14. title:'上传中...'
  15. })
  16. const uploadResArr=tempFilePaths.map(item=>{
  17. return uploadToServer(item)
  18. })
  19. return new Promise((resolve,reject)=>{
  20. Promise.all(uploadResArr).then(res=>{
  21. uni.hideLoading()
  22. const arr=res.map(item=>{
  23. return item
  24. })
  25. resolve(arr)
  26. }).catch(res=>{
  27. uni.hideLoading()
  28. })
  29. })
  30. }
  31. /**
  32. * 上传文件
  33. * count 同时上传文件数
  34. * type 能选择文件类型
  35. */
  36. export const uploadFiles=async ({count=1,type='all'})=>{
  37. const tempFilePaths=await asyncChooseFiles({count,type})
  38. uni.showLoading({
  39. title:'上传中...'
  40. })
  41. const uploadResArr=tempFilePaths.map(item=>{
  42. return uploadToServer(item.path)
  43. })
  44. return new Promise((resolve,reject)=>{
  45. Promise.all(uploadResArr).then(res=>{
  46. uni.hideLoading()
  47. const arr=res.map(item=>{
  48. return item
  49. })
  50. resolve(arr)
  51. }).catch(res=>{
  52. uni.hideLoading()
  53. })
  54. })
  55. }
  56. /**
  57. * 选择文件
  58. */
  59. const asyncChooseFiles=({count,type})=>{
  60. return new Promise((resolve,reject)=>{
  61. wx.chooseMessageFile({
  62. count:count,
  63. type:type,
  64. success:(res)=>{
  65. resolve(res.tempFiles)
  66. },
  67. fail:(error)=>{
  68. console.log(error.errMsg);
  69. if(error.errMsg.search('not supported')!=-1){
  70. uni.showToast({
  71. title:'请通过手机上传附件',
  72. icon:'none'
  73. })
  74. }
  75. }
  76. })
  77. })
  78. }
  79. /**
  80. * 上传文件到服务器
  81. */
  82. const uploadToServer=async (path)=>{
  83. const temres=await uniAsync.uploadFile({
  84. url:baseUrl+'/resource/upload',
  85. filePath:path,
  86. name:'file',
  87. header:{
  88. Authorization:store.state.token
  89. }
  90. })
  91. const res=JSON.parse(temres.data)
  92. if(res.code===200){
  93. return res.data.ResourceUrl
  94. }
  95. }