|
|
@@ -1,5 +1,6 @@
|
|
|
import { FastifyRequest, FastifyReply, FastifyInstance } from 'fastify'
|
|
|
import { RecordsService } from '../services/records.service'
|
|
|
+import { FileService } from '../services/file.service'
|
|
|
import {
|
|
|
ListRecordsQuery,
|
|
|
CreateRecordsBody,
|
|
|
@@ -8,9 +9,67 @@ import {
|
|
|
|
|
|
export class RecordsController {
|
|
|
private recordsService: RecordsService
|
|
|
+ private fileService: FileService
|
|
|
|
|
|
constructor(app: FastifyInstance) {
|
|
|
this.recordsService = new RecordsService(app)
|
|
|
+ this.fileService = new FileService(app)
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 上传文件并创建记录
|
|
|
+ */
|
|
|
+ async uploadAndCreate(request: FastifyRequest, reply: FastifyReply) {
|
|
|
+ try {
|
|
|
+ const data = await request.file()
|
|
|
+
|
|
|
+ if (!data) {
|
|
|
+ return reply.code(400).send({ message: '请选择要上传的文件' })
|
|
|
+ }
|
|
|
+
|
|
|
+ const buffer = await data.toBuffer()
|
|
|
+ const filename = data.filename
|
|
|
+ const mimeType = data.mimetype
|
|
|
+
|
|
|
+ // 从表单字段中获取描述
|
|
|
+ const description = (data.fields?.description as any)?.value || ''
|
|
|
+
|
|
|
+ // 上传文件到OSS
|
|
|
+ const uploadResult = await this.fileService.uploadFile(buffer, filename, mimeType, {
|
|
|
+ folder: 'tweb',
|
|
|
+ maxSize: 50 * 1024 * 1024 // 50MB
|
|
|
+ })
|
|
|
+
|
|
|
+ // 创建记录
|
|
|
+ const record = await this.recordsService.create(uploadResult.url, description)
|
|
|
+
|
|
|
+ return reply.code(201).send({
|
|
|
+ message: '文件上传并创建记录成功',
|
|
|
+ data: {
|
|
|
+ record: {
|
|
|
+ id: record.id,
|
|
|
+ url: record.url,
|
|
|
+ description: record.description,
|
|
|
+ createdAt: record.createdAt,
|
|
|
+ updatedAt: record.updatedAt
|
|
|
+ },
|
|
|
+ file: {
|
|
|
+ filename: filename,
|
|
|
+ originalName: filename,
|
|
|
+ url: uploadResult.url,
|
|
|
+ key: uploadResult.key,
|
|
|
+ size: uploadResult.size,
|
|
|
+ mimeType: uploadResult.mimeType,
|
|
|
+ dateFolder: new Date().toISOString().split('T')[0]
|
|
|
+ }
|
|
|
+ }
|
|
|
+ })
|
|
|
+ } catch (error) {
|
|
|
+ return reply.code(500).send({
|
|
|
+ message: '文件上传并创建记录失败',
|
|
|
+ error: error instanceof Error ? error.message : '未知错误'
|
|
|
+ })
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
async create(request: FastifyRequest<{ Body: CreateRecordsBody }>, reply: FastifyReply) {
|