choose-and-upload-file.js 8.2 KB

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