choose-and-upload-file.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. 'use strict';
  2. import FileApi from '@/sheep/api/infra/file';
  3. const ERR_MSG_OK = 'chooseAndUploadFile:ok';
  4. const ERR_MSG_FAIL = 'chooseAndUploadFile:fail';
  5. function chooseImage(opts) {
  6. const {
  7. count,
  8. sizeType = ['original', 'compressed'],
  9. sourceType = ['album', 'camera'],
  10. extension,
  11. } = opts;
  12. return new Promise((resolve, reject) => {
  13. uni.chooseImage({
  14. count,
  15. sizeType,
  16. sourceType,
  17. extension,
  18. success(res) {
  19. resolve(normalizeChooseAndUploadFileRes(res, 'image'));
  20. },
  21. fail(res) {
  22. reject({
  23. errMsg: res.errMsg.replace('chooseImage:fail', ERR_MSG_FAIL),
  24. });
  25. },
  26. });
  27. });
  28. }
  29. function chooseVideo(opts) {
  30. const { camera, compressed, maxDuration, sourceType = ['album', 'camera'], extension } = opts;
  31. return new Promise((resolve, reject) => {
  32. uni.chooseVideo({
  33. camera,
  34. compressed,
  35. maxDuration,
  36. sourceType,
  37. extension,
  38. success(res) {
  39. const { tempFilePath, duration, size, height, width } = res;
  40. resolve(
  41. normalizeChooseAndUploadFileRes(
  42. {
  43. errMsg: 'chooseVideo:ok',
  44. tempFilePaths: [tempFilePath],
  45. tempFiles: [
  46. {
  47. name: (res.tempFile && res.tempFile.name) || '',
  48. path: tempFilePath,
  49. size,
  50. type: (res.tempFile && res.tempFile.type) || '',
  51. width,
  52. height,
  53. duration,
  54. fileType: 'video',
  55. cloudPath: '',
  56. },
  57. ],
  58. },
  59. 'video',
  60. ),
  61. );
  62. },
  63. fail(res) {
  64. reject({
  65. errMsg: res.errMsg.replace('chooseVideo:fail', ERR_MSG_FAIL),
  66. });
  67. },
  68. });
  69. });
  70. }
  71. function chooseAll(opts) {
  72. const { count, extension } = opts;
  73. return new Promise((resolve, reject) => {
  74. let chooseFile = uni.chooseFile;
  75. if (typeof wx !== 'undefined' && typeof wx.chooseMessageFile === 'function') {
  76. chooseFile = wx.chooseMessageFile;
  77. }
  78. if (typeof chooseFile !== 'function') {
  79. return reject({
  80. errMsg: ERR_MSG_FAIL + ' 请指定 type 类型,该平台仅支持选择 image 或 video。',
  81. });
  82. }
  83. chooseFile({
  84. type: 'all',
  85. count,
  86. extension,
  87. success(res) {
  88. resolve(normalizeChooseAndUploadFileRes(res));
  89. },
  90. fail(res) {
  91. reject({
  92. errMsg: res.errMsg.replace('chooseFile:fail', ERR_MSG_FAIL),
  93. });
  94. },
  95. });
  96. });
  97. }
  98. function normalizeChooseAndUploadFileRes(res, fileType) {
  99. res.tempFiles.forEach((item, index) => {
  100. if (!item.name) {
  101. item.name = item.path.substring(item.path.lastIndexOf('/') + 1);
  102. }
  103. if (fileType) {
  104. item.fileType = fileType;
  105. }
  106. item.cloudPath = Date.now() + '_' + index + item.name.substring(item.name.lastIndexOf('.'));
  107. });
  108. if (!res.tempFilePaths) {
  109. res.tempFilePaths = res.tempFiles.map((file) => file.path);
  110. }
  111. return res;
  112. }
  113. function convertToArrayBuffer(uniFile) {
  114. return new Promise((resolve, reject) => {
  115. const fs = uni.getFileSystemManager();
  116. fs.readFile({
  117. filePath: uniFile.path, // 确保路径正确
  118. success: (fileRes) => {
  119. try {
  120. // 将读取的内容转换为 ArrayBuffer
  121. const arrayBuffer = new Uint8Array(fileRes.data).buffer;
  122. resolve(arrayBuffer);
  123. } catch (error) {
  124. reject(new Error(`转换为 ArrayBuffer 失败: ${error.message}`));
  125. }
  126. },
  127. fail: (error) => {
  128. reject(new Error(`读取文件失败: ${error.errMsg}`));
  129. },
  130. });
  131. });
  132. }
  133. function uploadCloudFiles(files, max = 5, onUploadProgress) {
  134. files = JSON.parse(JSON.stringify(files));
  135. const len = files.length;
  136. let count = 0;
  137. let self = this;
  138. return new Promise((resolve) => {
  139. while (count < max) {
  140. next();
  141. }
  142. function next() {
  143. let cur = count++;
  144. if (cur >= len) {
  145. !files.find((item) => !item.url && !item.errMsg) && resolve(files);
  146. return;
  147. }
  148. const fileItem = files[cur];
  149. const index = self.files.findIndex((v) => v.uuid === fileItem.uuid);
  150. fileItem.url = '';
  151. delete fileItem.errMsg;
  152. uniCloud
  153. .uploadFile({
  154. filePath: fileItem.path,
  155. cloudPath: fileItem.cloudPath,
  156. fileType: fileItem.fileType,
  157. onUploadProgress: (res) => {
  158. res.index = index;
  159. onUploadProgress && onUploadProgress(res);
  160. },
  161. })
  162. .then((res) => {
  163. fileItem.url = res.fileID;
  164. fileItem.index = index;
  165. if (cur < len) {
  166. next();
  167. }
  168. })
  169. .catch((res) => {
  170. fileItem.errMsg = res.errMsg || res.message;
  171. fileItem.index = index;
  172. if (cur < len) {
  173. next();
  174. }
  175. });
  176. }
  177. });
  178. }
  179. async function uploadFiles(choosePromise, { onChooseFile, onUploadProgress }) {
  180. // 获取选择的文件
  181. const res = await choosePromise;
  182. // 处理文件选择回调
  183. let files = res.tempFiles || [];
  184. if (onChooseFile) {
  185. const customChooseRes = onChooseFile(res);
  186. if (typeof customChooseRes !== 'undefined') {
  187. files = await Promise.resolve(customChooseRes);
  188. if (typeof files === 'undefined') {
  189. files = res.tempFiles || []; // Fallback
  190. }
  191. }
  192. }
  193. // 如果是前端直连上传
  194. if (UPLOAD_TYPE.CLIENT === import.meta.env.SHOPRO_UPLOAD_TYPE) {
  195. // 为上传创建一组 Promise
  196. const uploadPromises = files.map(async (file) => {
  197. try {
  198. // 1.1 获取文件预签名地址
  199. const { data: presignedInfo } = await FileApi.getFilePresignedUrl(file.name);
  200. // 1.2 获取二进制文件对象
  201. const fileBuffer = await convertToArrayBuffer(file);
  202. // 返回上传的 Promise
  203. return new Promise((resolve, reject) => {
  204. uni.request({
  205. url: presignedInfo.uploadUrl, // 预签名的上传 URL
  206. method: 'PUT', // 使用 PUT 方法
  207. header: {
  208. 'Content-Type':
  209. file.fileType + '/' + file.name.substring(file.name.lastIndexOf('.') + 1), // 设置内容类型
  210. },
  211. data: fileBuffer, // 文件的路径,适用于小程序
  212. success: (res) => {
  213. // 1.4. 记录文件信息到后端(异步)
  214. createFile(presignedInfo, file);
  215. // 1.5. 重新赋值
  216. file.url = presignedInfo.url;
  217. console.log('上传成功:', res);
  218. resolve(file);
  219. },
  220. fail: (err) => {
  221. console.error('上传失败:', err);
  222. reject(err);
  223. },
  224. });
  225. });
  226. } catch (error) {
  227. console.error('上传失败:', error);
  228. throw error;
  229. }
  230. });
  231. // 等待所有上传完成
  232. return await Promise.all(uploadPromises); // 返回已上传的文件列表
  233. } else {
  234. // 后端上传
  235. for (let file of files) {
  236. const { data } = await FileApi.uploadFile(file.path);
  237. file.url = data;
  238. }
  239. return files;
  240. }
  241. }
  242. function chooseAndUploadFile(
  243. opts = {
  244. type: 'all',
  245. },
  246. ) {
  247. if (opts.type === 'image') {
  248. return uploadFiles(chooseImage(opts), opts);
  249. } else if (opts.type === 'video') {
  250. return uploadFiles(chooseVideo(opts), opts);
  251. }
  252. return uploadFiles(chooseAll(opts), opts);
  253. }
  254. /**
  255. * 创建文件信息
  256. * @param vo 文件预签名信息
  257. * @param file 文件
  258. */
  259. function createFile(vo, file) {
  260. const fileVo = {
  261. configId: vo.configId,
  262. url: vo.url,
  263. path: file.name,
  264. name: file.name,
  265. type: file.fileType,
  266. size: file.size,
  267. };
  268. FileApi.createFile(fileVo);
  269. return fileVo;
  270. }
  271. /**
  272. * 上传类型
  273. */
  274. const UPLOAD_TYPE = {
  275. // 客户端直接上传(只支持S3服务)
  276. CLIENT: 'client',
  277. // 客户端发送到后端上传
  278. SERVER: 'server',
  279. };
  280. export { chooseAndUploadFile, uploadCloudFiles };