file.service.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. import { GenericCrudService } from '@/server/utils/generic-crud.service';
  2. import { DataSource } from 'typeorm';
  3. import { File } from './file.entity';
  4. import { MinioService } from './minio.service';
  5. import { v4 as uuidv4 } from 'uuid';
  6. import { logger } from '@/server/utils/logger';
  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. // 返回文件记录和上传策略
  33. return {
  34. file: savedFile,
  35. uploadPolicy
  36. };
  37. } catch (error) {
  38. logger.error('Failed to create file:', error);
  39. throw new Error('文件创建失败');
  40. }
  41. }
  42. /**
  43. * 删除文件记录及对应的MinIO文件
  44. */
  45. async deleteFile(id: number) {
  46. // 获取文件记录
  47. const file = await this.getById(id);
  48. if (!file) {
  49. throw new Error('文件不存在');
  50. }
  51. try {
  52. // 验证文件是否存在于MinIO
  53. const fileExists = await this.minioService.objectExists(this.minioService.bucketName, file.path);
  54. if (!fileExists) {
  55. logger.error(`File not found in MinIO: ${this.minioService.bucketName}/${file.path}`);
  56. // 仍然继续删除数据库记录,但记录警告日志
  57. } else {
  58. // 从MinIO删除文件
  59. await this.minioService.deleteObject(this.minioService.bucketName, file.path);
  60. }
  61. // 从数据库删除记录
  62. await this.delete(id);
  63. return true;
  64. } catch (error) {
  65. logger.error('Failed to delete file:', error);
  66. throw new Error('文件删除失败');
  67. }
  68. }
  69. /**
  70. * 获取文件访问URL
  71. */
  72. async getFileUrl(id: number) {
  73. const file = await this.getById(id);
  74. if (!file) {
  75. throw new Error('文件不存在');
  76. }
  77. return this.minioService.getPresignedFileUrl(this.minioService.bucketName, file.path);
  78. }
  79. /**
  80. * 获取文件下载URL(带Content-Disposition头)
  81. */
  82. async getFileDownloadUrl(id: number) {
  83. const file = await this.getById(id);
  84. if (!file) {
  85. throw new Error('文件不存在');
  86. }
  87. const url = await this.minioService.getPresignedFileDownloadUrl(
  88. this.minioService.bucketName,
  89. file.path,
  90. file.name
  91. );
  92. return {
  93. url,
  94. filename: file.name
  95. };
  96. }
  97. /**
  98. * 创建多部分上传策略
  99. */
  100. async createMultipartUploadPolicy(data: Partial<File>, partCount: number) {
  101. try {
  102. // 生成唯一文件存储路径
  103. const fileKey = `${data.uploadUserId}/${uuidv4()}-${data.name}`;
  104. // 初始化多部分上传
  105. const uploadId = await this.minioService.createMultipartUpload(
  106. this.minioService.bucketName,
  107. fileKey
  108. );
  109. // 生成各部分上传URL
  110. const uploadUrls = await this.minioService.generateMultipartUploadUrls(
  111. this.minioService.bucketName,
  112. fileKey,
  113. uploadId,
  114. partCount
  115. );
  116. // 准备文件记录数据
  117. const fileData = {
  118. ...data,
  119. path: fileKey,
  120. uploadTime: new Date(),
  121. createdAt: new Date(),
  122. updatedAt: new Date()
  123. };
  124. // 保存文件记录到数据库
  125. const savedFile = await this.create(fileData as File);
  126. // 返回文件记录和上传策略
  127. return {
  128. file: savedFile,
  129. uploadId,
  130. uploadUrls,
  131. bucket: this.minioService.bucketName,
  132. key: fileKey
  133. };
  134. } catch (error) {
  135. logger.error('Failed to create multipart upload policy:', error);
  136. throw new Error('创建多部分上传策略失败');
  137. }
  138. }
  139. /**
  140. * 完成分片上传
  141. */
  142. async completeMultipartUpload(data: {
  143. uploadId: string;
  144. bucket: string;
  145. key: string;
  146. parts: Array<{ partNumber: number; etag: string }>;
  147. }) {
  148. logger.db('Starting multipart upload completion:', {
  149. uploadId: data.uploadId,
  150. bucket: data.bucket,
  151. key: data.key,
  152. partsCount: data.parts.length
  153. });
  154. // 查找文件记录
  155. const file = await this.repository.findOneBy({ path: data.key });
  156. if (!file) {
  157. throw new Error('文件记录不存在');
  158. }
  159. try {
  160. // 完成MinIO分片上传 - 注意格式转换
  161. const result = await this.minioService.completeMultipartUpload(
  162. data.bucket,
  163. data.key,
  164. data.uploadId,
  165. data.parts.map(part => ({ PartNumber: part.partNumber, ETag: part.etag }))
  166. );
  167. // 更新文件大小等信息
  168. file.size = result.size;
  169. file.updatedAt = new Date();
  170. await this.repository.save(file);
  171. // 生成文件访问URL
  172. const url = this.minioService.getFileUrl(data.bucket, data.key);
  173. logger.db('Multipart upload completed successfully:', {
  174. fileId: file.id,
  175. size: result.size,
  176. key: data.key
  177. });
  178. return {
  179. fileId: file.id,
  180. url,
  181. key: data.key,
  182. size: result.size
  183. };
  184. } catch (error) {
  185. logger.error('Failed to complete multipart upload:', error);
  186. throw new Error('完成分片上传失败');
  187. }
  188. }
  189. }