file.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import {
  2. baseUrl,
  3. apiPath
  4. } from '@/sheep/config';
  5. import request from '@/sheep/request';
  6. const FileApi = {
  7. // 上传文件
  8. uploadFile: (file) => {
  9. // TODO 非繁人:访问令牌的接入;
  10. const token = uni.getStorageSync('token');
  11. uni.showLoading({
  12. title: '上传中',
  13. });
  14. return new Promise((resolve, reject) => {
  15. uni.uploadFile({
  16. url: baseUrl + apiPath + '/infra/file/upload',
  17. filePath: file,
  18. name: 'file',
  19. header: {
  20. // Accept: 'text/json',
  21. Accept: '*/*',
  22. 'tenant-id': '1',
  23. // Authorization: 'Bearer test247',
  24. },
  25. success: (uploadFileRes) => {
  26. let result = JSON.parse(uploadFileRes.data);
  27. if (result.error === 1) {
  28. uni.showToast({
  29. icon: 'none',
  30. title: result.msg,
  31. });
  32. } else {
  33. return resolve(result);
  34. }
  35. },
  36. fail: (error) => {
  37. console.log('上传失败:', error);
  38. return resolve(false);
  39. },
  40. complete: () => {
  41. uni.hideLoading();
  42. },
  43. });
  44. });
  45. },
  46. // 通过图片url获得文件流
  47. getFileIO: async (fileUrl) => {
  48. // #ifdef MP-WEIXIN
  49. return new Promise((resolve, reject) => {
  50. wx.request({
  51. url: `${import.meta.env.SHOPRO_BASE_URL}/app-api/infra/file/downloadByUrl`,
  52. method: 'GET',
  53. data: {
  54. fileUrl
  55. },
  56. responseType: 'arraybuffer',
  57. success: (res) => {
  58. if (res.statusCode === 200) {
  59. const base64 = wx.arrayBufferToBase64(res.data);
  60. resolve(base64);
  61. } else {
  62. reject(new Error('网络响应不是OK状态'));
  63. }
  64. },
  65. fail: (err) => {
  66. reject(err);
  67. }
  68. });
  69. });
  70. // #endif
  71. // #ifndef MP-WEIXIN
  72. const response = await fetch(import.meta.env.SHOPRO_BASE_URL + '/app-api/infra/file/downloadByUrl?fileUrl=' + fileUrl, {method: 'GET',})
  73. if (!response.ok) {
  74. throw new Error('网络响应不是OK状态');
  75. }
  76. const blob = await response.blob();
  77. return blob;
  78. // #endif
  79. },
  80. };
  81. export default FileApi;