file.service.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. import { GenericCrudService } from '@d8d/shared-crud';
  2. import { DataSource } from 'typeorm';
  3. import { File } from '../entities/file.entity';
  4. import { MinioService } from './minio.service';
  5. import { v4 as uuidv4 } from 'uuid';
  6. import { logger } from '@d8d/shared-utils';
  7. export class FileService extends GenericCrudService<File> {
  8. private readonly minioService: MinioService;
  9. constructor(dataSource: DataSource) {
  10. super(dataSource, File);
  11. this.minioService = new MinioService();
  12. }
  13. /**
  14. * 创建文件记录并生成预签名上传URL
  15. */
  16. async createFile(data: Partial<File>) {
  17. try {
  18. // 生成唯一文件存储路径
  19. const fileKey = `${data.uploadUserId}/${uuidv4()}-${data.name}`;
  20. // 生成MinIO上传策略
  21. const uploadPolicy = await this.minioService.generateUploadPolicy(fileKey);
  22. // 准备文件记录数据
  23. const fileData = {
  24. ...data,
  25. path: fileKey,
  26. uploadTime: new Date(),
  27. createdAt: new Date(),
  28. updatedAt: new Date()
  29. };
  30. // 保存文件记录到数据库
  31. const savedFile = await this.create(fileData as File);
  32. // 重新加载文件记录,包含关联的uploadUser数据
  33. const fileWithUser = await this.repository.findOne({
  34. where: { id: savedFile.id },
  35. relations: ['uploadUser']
  36. });
  37. // 返回文件记录和上传策略
  38. return {
  39. file: fileWithUser || savedFile,
  40. uploadPolicy
  41. };
  42. } catch (error) {
  43. logger.error('Failed to create file:', error);
  44. throw new Error('文件创建失败');
  45. }
  46. }
  47. /**
  48. * 删除文件记录及对应的MinIO文件
  49. */
  50. async deleteFile(id: number) {
  51. const file = await this.repository.findOne({ where: { id } });
  52. if (!file) {
  53. throw new Error('文件不存在');
  54. }
  55. try {
  56. // 验证文件是否存在于MinIO
  57. const fileExists = await this.minioService.objectExists(this.minioService.bucketName, file.path);
  58. if (!fileExists) {
  59. logger.error(`File not found in MinIO: ${this.minioService.bucketName}/${file.path}`);
  60. // 仍然继续删除数据库记录,但记录警告日志
  61. } else {
  62. // 从MinIO删除文件
  63. await this.minioService.deleteObject(this.minioService.bucketName, file.path);
  64. }
  65. // 从数据库删除记录
  66. await this.delete(id);
  67. return true;
  68. } catch (error) {
  69. logger.error('Failed to delete file:', error);
  70. throw new Error('文件删除失败');
  71. }
  72. }
  73. /**
  74. * 获取文件访问URL
  75. */
  76. async getFileUrl(id: number) {
  77. const file = await this.getById(id);
  78. if (!file) {
  79. throw new Error('文件不存在');
  80. }
  81. return this.minioService.getPresignedFileUrl(this.minioService.bucketName, file.path);
  82. }
  83. /**
  84. * 获取文件下载URL(带Content-Disposition头)
  85. */
  86. async getFileDownloadUrl(id: number) {
  87. const file = await this.getById(id);
  88. if (!file) {
  89. throw new Error('文件不存在');
  90. }
  91. const url = await this.minioService.getPresignedFileDownloadUrl(
  92. this.minioService.bucketName,
  93. file.path,
  94. file.name
  95. );
  96. return {
  97. url,
  98. filename: file.name
  99. };
  100. }
  101. /**
  102. * 创建多部分上传策略
  103. */
  104. async createMultipartUploadPolicy(data: Partial<File>, partCount: number) {
  105. try {
  106. // 生成唯一文件存储路径
  107. const fileKey = `${data.uploadUserId}/${uuidv4()}-${data.name}`;
  108. // 初始化多部分上传
  109. const uploadId = await this.minioService.createMultipartUpload(
  110. this.minioService.bucketName,
  111. fileKey
  112. );
  113. // 生成各部分上传URL
  114. const uploadUrls = await this.minioService.generateMultipartUploadUrls(
  115. this.minioService.bucketName,
  116. fileKey,
  117. uploadId,
  118. partCount
  119. );
  120. // 准备文件记录数据
  121. const fileData = {
  122. ...data,
  123. path: fileKey,
  124. uploadTime: new Date(),
  125. createdAt: new Date(),
  126. updatedAt: new Date()
  127. };
  128. // 保存文件记录到数据库
  129. const savedFile = await this.create(fileData as File);
  130. // 返回文件记录和上传策略
  131. return {
  132. file: savedFile,
  133. uploadId,
  134. uploadUrls,
  135. bucket: this.minioService.bucketName,
  136. key: fileKey
  137. };
  138. } catch (error) {
  139. logger.error('Failed to create multipart upload policy:', error);
  140. throw new Error('创建多部分上传策略失败');
  141. }
  142. }
  143. /**
  144. * 完成分片上传
  145. */
  146. async completeMultipartUpload(data: {
  147. uploadId: string;
  148. bucket: string;
  149. key: string;
  150. parts: Array<{ partNumber: number; etag: string }>;
  151. }) {
  152. logger.db('Starting multipart upload completion:', {
  153. uploadId: data.uploadId,
  154. bucket: data.bucket,
  155. key: data.key,
  156. partsCount: data.parts.length
  157. });
  158. // 查找文件记录
  159. const file = await this.repository.findOneBy({ path: data.key });
  160. if (!file) {
  161. throw new Error('文件记录不存在');
  162. }
  163. try {
  164. // 完成MinIO分片上传 - 注意格式转换
  165. const result = await this.minioService.completeMultipartUpload(
  166. data.bucket,
  167. data.key,
  168. data.uploadId,
  169. data.parts.map(part => ({ PartNumber: part.partNumber, ETag: part.etag }))
  170. );
  171. // 更新文件大小等信息
  172. file.size = result.size;
  173. file.updatedAt = new Date();
  174. await this.repository.save(file);
  175. // 生成文件访问URL
  176. const url = this.minioService.getFileUrl(data.bucket, data.key);
  177. logger.db('Multipart upload completed successfully:', {
  178. fileId: file.id,
  179. size: result.size,
  180. key: data.key
  181. });
  182. return {
  183. fileId: file.id,
  184. url,
  185. key: data.key,
  186. size: result.size
  187. };
  188. } catch (error) {
  189. logger.error('Failed to complete multipart upload:', error);
  190. throw new Error('完成分片上传失败');
  191. }
  192. }
  193. /**
  194. * 保存文件记录并将文件内容直接上传到MinIO
  195. * @param fileData - 文件基础信息
  196. * @param fileContent - 文件内容(Buffer)
  197. * @param contentType - 文件MIME类型
  198. * @returns 保存的文件记录和文件访问URL
  199. */
  200. async saveFile(
  201. fileData: {
  202. name: string;
  203. size: number;
  204. mimeType: string;
  205. uploadUserId: number;
  206. [key: string]: any;
  207. },
  208. fileContent: Buffer,
  209. contentType?: string
  210. ) {
  211. try {
  212. logger.db('Starting saveFile process:', {
  213. filename: fileData.name,
  214. size: fileData.size,
  215. mimeType: fileData.mimeType,
  216. uploadUserId: fileData.uploadUserId
  217. });
  218. // 生成唯一文件存储路径
  219. const fileKey = `${fileData.uploadUserId}/${uuidv4()}-${fileData.name}`;
  220. // 确保存储桶存在
  221. await this.minioService.ensureBucketExists();
  222. // 直接上传文件内容到MinIO
  223. const fileUrl = await this.minioService.createObject(
  224. this.minioService.bucketName,
  225. fileKey,
  226. fileContent,
  227. contentType || fileData.mimeType
  228. );
  229. // 准备文件记录数据
  230. const completeFileData = {
  231. ...fileData,
  232. path: fileKey,
  233. uploadTime: new Date(),
  234. };
  235. // 保存文件记录到数据库
  236. const savedFile = await this.create(completeFileData as any);
  237. logger.db('File saved successfully:', {
  238. fileId: savedFile.id,
  239. filename: savedFile.name,
  240. size: savedFile.size,
  241. url: fileUrl
  242. });
  243. return {
  244. file: savedFile,
  245. url: fileUrl
  246. };
  247. } catch (error) {
  248. logger.error('Failed to save file:', error);
  249. throw new Error(`文件保存失败: ${error instanceof Error ? error.message : '未知错误'}`);
  250. }
  251. }
  252. /**
  253. * 保存文件记录并将文件内容直接上传到MinIO(支持自定义存储路径)
  254. * @param fileData - 文件基础信息
  255. * @param fileContent - 文件内容(Buffer)
  256. * @param customPath - 自定义存储路径(可选)
  257. * @param contentType - 文件MIME类型
  258. * @returns 保存的文件记录和文件访问URL
  259. */
  260. async saveFileWithCustomPath(
  261. fileData: {
  262. name: string;
  263. size: number;
  264. mimeType: string;
  265. uploadUserId: number;
  266. [key: string]: any;
  267. },
  268. fileContent: Buffer,
  269. customPath?: string,
  270. contentType?: string
  271. ) {
  272. try {
  273. logger.db('Starting saveFileWithCustomPath process:', {
  274. filename: fileData.name,
  275. size: fileData.size,
  276. mimeType: fileData.mimeType,
  277. uploadUserId: fileData.uploadUserId,
  278. customPath: customPath || 'auto-generated'
  279. });
  280. // 使用自定义路径或生成唯一文件存储路径
  281. const fileKey = customPath || `${fileData.uploadUserId}/${uuidv4()}-${fileData.name}`;
  282. // 确保存储桶存在
  283. await this.minioService.ensureBucketExists();
  284. // 直接上传文件内容到MinIO
  285. const fileUrl = await this.minioService.createObject(
  286. this.minioService.bucketName,
  287. fileKey,
  288. fileContent,
  289. contentType || fileData.mimeType
  290. );
  291. // 准备文件记录数据
  292. const completeFileData = {
  293. ...fileData,
  294. path: fileKey,
  295. uploadTime: new Date(),
  296. // createdAt: new Date(),
  297. // updatedAt: new Date()
  298. };
  299. // 保存文件记录到数据库
  300. const savedFile = await this.create(completeFileData as any);
  301. logger.db('File saved with custom path successfully:', {
  302. fileId: savedFile.id,
  303. filename: savedFile.name,
  304. size: savedFile.size,
  305. path: fileKey,
  306. url: fileUrl
  307. });
  308. return {
  309. file: savedFile,
  310. url: fileUrl
  311. };
  312. } catch (error) {
  313. logger.error('Failed to save file with custom path:', error);
  314. throw new Error(`文件保存失败: ${error instanceof Error ? error.message : '未知错误'}`);
  315. }
  316. }
  317. /**
  318. * 从URL下载文件并保存到MinIO
  319. * @param url - 文件URL
  320. * @param fileData - 文件基础信息(不含name和size,将自动获取)
  321. * @param options - 可选配置
  322. * @returns 保存的文件记录和文件访问URL
  323. */
  324. async downloadAndSaveFromUrl(
  325. url: string,
  326. fileData: {
  327. uploadUserId: number;
  328. mimeType?: string;
  329. customFileName?: string;
  330. customPath?: string;
  331. [key: string]: any;
  332. },
  333. options?: {
  334. timeout?: number;
  335. retries?: number;
  336. }
  337. ) {
  338. try {
  339. const axios = require('axios');
  340. logger.db('Starting downloadAndSaveFromUrl process:', {
  341. url,
  342. uploadUserId: fileData.uploadUserId,
  343. customFileName: fileData.customFileName,
  344. customPath: fileData.customPath
  345. });
  346. // 下载文件
  347. const response = await axios.get(url, {
  348. responseType: 'arraybuffer',
  349. timeout: options?.timeout || 30000,
  350. maxRedirects: 5,
  351. headers: {
  352. 'User-Agent': 'Mozilla/5.0 (compatible; FileDownloader/1.0)'
  353. }
  354. });
  355. const buffer = Buffer.from(response.data);
  356. // 从URL或响应头中获取文件名
  357. let fileName = fileData.customFileName;
  358. if (!fileName) {
  359. // 尝试从Content-Disposition头获取文件名
  360. const contentDisposition = response.headers['content-disposition'];
  361. if (contentDisposition) {
  362. const filenameMatch = contentDisposition.match(/filename[*]?=(?:utf-8'')?(.+)/i);
  363. if (filenameMatch) {
  364. fileName = decodeURIComponent(filenameMatch[1].replace(/['"]/g, ''));
  365. }
  366. }
  367. // 从URL路径获取文件名
  368. if (!fileName) {
  369. const urlPath = new URL(url).pathname;
  370. fileName = urlPath.split('/').pop() || `file_${Date.now()}`;
  371. }
  372. }
  373. // 确保文件有扩展名
  374. if (!fileName.includes('.') && fileData.mimeType) {
  375. const ext = this.getExtensionFromMimeType(fileData.mimeType);
  376. if (ext) {
  377. fileName += `.${ext}`;
  378. }
  379. }
  380. // 确定MIME类型
  381. let mimeType = fileData.mimeType || response.headers['content-type'];
  382. if (!mimeType || mimeType === 'application/octet-stream') {
  383. mimeType = this.inferMimeType(fileName);
  384. }
  385. // 保存文件
  386. const saveResult = await this.saveFileWithCustomPath(
  387. {
  388. ...fileData,
  389. name: fileName,
  390. size: buffer.length,
  391. mimeType,
  392. fileType: this.getFileTypeFromMimeType(mimeType)
  393. },
  394. buffer,
  395. fileData.customPath,
  396. mimeType
  397. );
  398. logger.db('Download and save completed successfully:', {
  399. fileId: saveResult.file.id,
  400. fileName,
  401. size: buffer.length,
  402. url: saveResult.url
  403. });
  404. return saveResult;
  405. } catch (error) {
  406. logger.error('Failed to download and save file from URL:', {
  407. url,
  408. error: error instanceof Error ? error.message : '未知错误',
  409. stack: error instanceof Error ? error.stack : undefined
  410. });
  411. throw new Error(`从URL下载文件失败: ${error instanceof Error ? error.message : '未知错误'}`);
  412. }
  413. }
  414. /**
  415. * 根据MIME类型获取文件扩展名
  416. */
  417. private getExtensionFromMimeType(mimeType: string): string | null {
  418. const mimeMap: Record<string, string> = {
  419. 'image/jpeg': 'jpg',
  420. 'image/png': 'png',
  421. 'image/gif': 'gif',
  422. 'image/webp': 'webp',
  423. 'image/svg+xml': 'svg',
  424. 'application/pdf': 'pdf',
  425. 'text/plain': 'txt',
  426. 'application/json': 'json',
  427. 'application/xml': 'xml',
  428. 'video/mp4': 'mp4',
  429. 'audio/mp3': 'mp3'
  430. };
  431. return mimeMap[mimeType] || null;
  432. }
  433. /**
  434. * 根据文件名推断MIME类型
  435. */
  436. private inferMimeType(fileName: string): string {
  437. const ext = fileName.toLowerCase().split('.').pop();
  438. const extMap: Record<string, string> = {
  439. 'jpg': 'image/jpeg',
  440. 'jpeg': 'image/jpeg',
  441. 'png': 'image/png',
  442. 'gif': 'image/gif',
  443. 'webp': 'image/webp',
  444. 'svg': 'image/svg+xml',
  445. 'pdf': 'application/pdf',
  446. 'txt': 'text/plain',
  447. 'json': 'application/json',
  448. 'xml': 'application/xml',
  449. 'mp4': 'video/mp4',
  450. 'mp3': 'audio/mp3',
  451. 'wav': 'audio/wav'
  452. };
  453. return extMap[ext || ''] || 'application/octet-stream';
  454. }
  455. /**
  456. * 根据MIME类型获取文件类型
  457. */
  458. private getFileTypeFromMimeType(mimeType: string): string {
  459. if (mimeType.startsWith('image/')) return 'image';
  460. if (mimeType.startsWith('video/')) return 'video';
  461. if (mimeType.startsWith('audio/')) return 'audio';
  462. if (mimeType === 'application/pdf') return 'document';
  463. if (mimeType.startsWith('text/')) return 'document';
  464. return 'other';
  465. }
  466. }