file.js 1.9 KB

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