uploadFile.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. })
  68. })
  69. }
  70. /**
  71. * 上传文件到服务器
  72. */
  73. const uploadToServer=async (path)=>{
  74. const temres=await uniAsync.uploadFile({
  75. url:baseUrl+'/resource/upload',
  76. filePath:path,
  77. name:'file',
  78. header:{
  79. Authorization:store.state.token
  80. }
  81. })
  82. const res=JSON.parse(temres.data)
  83. if(res.code===200){
  84. return res.data.ResourceUrl
  85. }
  86. }