choose-and-upload-file.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. 'use strict';
  2. import FileApi from '@/common/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. async function readFile(uniFile) {
  114. // 微信小程序
  115. if (uni.getFileSystemManager) {
  116. const fs = uni.getFileSystemManager();
  117. return fs.readFileSync(uniFile.path);
  118. }
  119. // H5 等
  120. return uniFile.arrayBuffer();
  121. }
  122. function uploadCloudFiles(files, max = 5, onUploadProgress) {
  123. files = JSON.parse(JSON.stringify(files));
  124. const len = files.length;
  125. let count = 0;
  126. let self = this;
  127. return new Promise((resolve) => {
  128. while (count < max) {
  129. next();
  130. }
  131. function next() {
  132. let cur = count++;
  133. if (cur >= len) {
  134. !files.find((item) => !item.url && !item.errMsg) && resolve(files);
  135. return;
  136. }
  137. const fileItem = files[cur];
  138. const index = self.files.findIndex((v) => v.uuid === fileItem.uuid);
  139. fileItem.url = '';
  140. delete fileItem.errMsg;
  141. uniCloud
  142. .uploadFile({
  143. filePath: fileItem.path,
  144. cloudPath: fileItem.cloudPath,
  145. fileType: fileItem.fileType,
  146. onUploadProgress: (res) => {
  147. res.index = index;
  148. onUploadProgress && onUploadProgress(res);
  149. },
  150. })
  151. .then((res) => {
  152. fileItem.url = res.fileID;
  153. fileItem.index = index;
  154. if (cur < len) {
  155. next();
  156. }
  157. })
  158. .catch((res) => {
  159. fileItem.errMsg = res.errMsg || res.message;
  160. fileItem.index = index;
  161. if (cur < len) {
  162. next();
  163. }
  164. });
  165. }
  166. });
  167. }
  168. function uploadFilesFromPath(path, directory) {
  169. // 目的:用于微信小程序,选择图片时,只有 path
  170. return uploadFiles(
  171. Promise.resolve({
  172. tempFiles: [
  173. {
  174. path,
  175. type: 'image/jpeg',
  176. name: path.includes('/') ? path.substring(path.lastIndexOf('/') + 1) : path,
  177. },
  178. ],
  179. }),
  180. {
  181. directory,
  182. },
  183. );
  184. }
  185. async function uploadFiles(choosePromise, { onChooseFile, onUploadProgress, directory }) {
  186. // 获取选择的文件
  187. const res = await choosePromise;
  188. // 处理文件选择回调
  189. let files = res.tempFiles || [];
  190. if (onChooseFile) {
  191. const customChooseRes = onChooseFile(res);
  192. if (typeof customChooseRes !== 'undefined') {
  193. files = await Promise.resolve(customChooseRes);
  194. if (typeof files === 'undefined') {
  195. files = res.tempFiles || []; // Fallback
  196. }
  197. }
  198. }
  199. // 如果是前端直连上传
  200. if (UPLOAD_TYPE.CLIENT === import.meta.env.SOUND_CHAIN_UPLOAD_TYPE) {
  201. // 为上传创建一组 Promise
  202. const uploadPromises = files.map(async (file) => {
  203. try {
  204. // 1.1 获取文件预签名地址
  205. const { data: presignedInfo } = await FileApi.getFilePresignedUrl(file.name, directory);
  206. // 1.2 获取二进制文件对象
  207. const fileBuffer = await readFile(file);
  208. // 返回上传的 Promise
  209. return new Promise((resolve, reject) => {
  210. // 1.3. 上传文件到 S3
  211. uni.request({
  212. url: presignedInfo.uploadUrl,
  213. method: 'PUT',
  214. header: {
  215. 'Content-Type': file.type,
  216. },
  217. data: fileBuffer,
  218. success: (res) => {
  219. // 1.4. 记录文件信息到后端(异步)
  220. createFile(presignedInfo, file);
  221. // 1.5. 重新赋值
  222. file.url = presignedInfo.url;
  223. resolve(file);
  224. },
  225. fail: (err) => {
  226. reject(err);
  227. },
  228. });
  229. });
  230. } catch (error) {
  231. console.error('上传失败:', error);
  232. throw error;
  233. }
  234. });
  235. // 等待所有上传完成
  236. return await Promise.all(uploadPromises); // 返回已上传的文件列表
  237. } else {
  238. // 后端上传
  239. for (let file of files) {
  240. const { data } = await FileApi.uploadFile(file.path, directory);
  241. file.url = data;
  242. }
  243. return files;
  244. }
  245. }
  246. function chooseAndUploadFile(
  247. opts = {
  248. type: 'all',
  249. directory: undefined,
  250. },
  251. ) {
  252. if (opts.type === 'image') {
  253. return uploadFiles(chooseImage(opts), opts);
  254. } else if (opts.type === 'video') {
  255. return uploadFiles(chooseVideo(opts), opts);
  256. }
  257. return uploadFiles(chooseAll(opts), opts);
  258. }
  259. /**
  260. * 创建文件信息
  261. * @param vo 文件预签名信息
  262. * @param file 文件
  263. */
  264. function createFile(vo, file) {
  265. const fileVo = {
  266. configId: vo.configId,
  267. url: vo.url,
  268. path: vo.path,
  269. name: file.name,
  270. type: file.fileType,
  271. size: file.size,
  272. };
  273. FileApi.createFile(fileVo);
  274. return fileVo;
  275. }
  276. /**
  277. * 上传类型
  278. */
  279. const UPLOAD_TYPE = {
  280. // 客户端直接上传(只支持S3服务)
  281. CLIENT: 'client',
  282. // 客户端发送到后端上传
  283. SERVER: 'server',
  284. };
  285. export { chooseAndUploadFile, uploadCloudFiles, uploadFilesFromPath };