feat: 文件上传api

This commit is contained in:
ilhamtahir committed 2024-11-19 19:54:41 +08:00
1 parent 516ec6d9bc
commit 0634862282
9 files changed
+602 -2

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
import {
Controller,
Post,
UploadedFile,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiBody, ApiConsumes, ApiOkResponse } from '@nestjs/swagger';
import { FileService } from '../service/file.service';
import { NoAuth } from '../decorators/no-auth.decorator';
import { FileVo } from '../vo/file.vo';
@Controller('files')
export class FileController {
constructor(private readonly fileService: FileService) {}
@Post('upload')
@ApiConsumes('multipart/form-data')
@NoAuth()
@ApiBody({
description: '上传文件',
schema: {
type: 'object',
properties: {
file: { type: 'string', format: 'binary' },
},
},
})
@ApiOkResponse({
type: FileVo,
})
@UseInterceptors(FileInterceptor('file'))
uploadFile(@UploadedFile() file: Express.Multer.File) {
return this.fileService.uploadFile(file);
}
}
+11 -1
View File
@@ -16,9 +16,17 @@ import { Permission } from './entity/permission.entity';
import { UserController } from './controller/user.controller';
import { UserBindService } from './service/user-bind.service';
import { UserBind } from './entity/user-bind.entity';
import { FileController } from './controller/file.controller';
import { FileService } from './service/file.service';
import { CosStrategy } from './service/storage-strategy/cos.strategy';
@Module({
controllers: [TokenController, RoleController, UserController],
controllers: [
TokenController,
RoleController,
UserController,
FileController,
],
imports: [
ConfigModule.forRoot({
isGlobal: true,
@@ -63,6 +71,8 @@ import { UserBind } from './entity/user-bind.entity';
AuthService,
RoleService,
UserBindService,
FileService,
CosStrategy,
],
exports: [UserService, UserBindService, AuthService],
})
+26
View File
@@ -0,0 +1,26 @@
import { FileStorage } from './storage-strategy/file-storage.interface';
import { CosStrategy } from './storage-strategy/cos.strategy';
import { Injectable } from '@nestjs/common';
import { FileVo } from '../vo/file.vo';
@Injectable()
export class FileService {
private readonly strategies: Record<string, FileStorage>;
constructor(private readonly cosStrategy: CosStrategy) {
this.strategies = {
cos: cosStrategy,
};
}
getStrategy(type: string): FileStorage {
return this.strategies[type] || this.cosStrategy;
}
async uploadFile(
file: Express.Multer.File,
options: any = { type: 'cos' },
): Promise<FileVo> {
return this.getStrategy(options.type).uploadFile(file, options);
}
}
@@ -0,0 +1,81 @@
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { FileStorage } from './file-storage.interface';
import { ConfigService } from '@nestjs/config';
import { v4 as uuidV4 } from 'uuid';
import * as COS from 'cos-nodejs-sdk-v5';
import { FileVo } from '../../vo/file.vo';
@Injectable()
export class CosStrategy implements FileStorage {
private client: COS;
private readonly bucket: string;
private readonly region: string;
constructor(private readonly configService: ConfigService) {
this.bucket = configService.get<string>('COS_BUCKET');
this.region = configService.get<string>('COS_REGION');
this.client = new COS({
SecretId: this.configService.get<string>('COS_SECRET_ID'),
SecretKey: this.configService.get<string>('COS_SECRET_KEY'),
});
}
async uploadFile(
file: Express.Multer.File,
options?: { folder?: string },
): Promise<FileVo> {
const folder = options.folder || 'uploads';
const key = `${folder}/${uuidV4()}-${file.originalname}`;
const result = await new Promise<COS.PutObjectResult>((resolve, reject) => {
this.client.putObject(
{
Bucket: this.bucket,
Region: this.region,
Key: key,
Body: file.buffer,
ContentType: file.mimetype,
},
(err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
},
);
});
if ('Location' in result) {
return { url: 'https://' + result.Location };
} else {
throw new HttpException(
'Failed to retrieve file URL from COS response',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
async deleteFile(filePath: string): Promise<void> {
const key = filePath.split('.com/')[1];
if (!key) {
throw new Error('Invalid filePath provided');
}
await new Promise<void>((resolve, reject) => {
this.client.deleteObject(
{
Bucket: this.bucket,
Region: this.region,
Key: key,
},
(err) => {
if (err) {
reject(err);
} else {
resolve();
}
},
);
});
}
}
@@ -0,0 +1,6 @@
import { FileVo } from '../../vo/file.vo';
export interface FileStorage {
uploadFile(file: Express.Multer.File, options?: any): Promise<FileVo>;
deleteFile(filePath: string): Promise<void>;
}
+9
View File
@@ -0,0 +1,9 @@
import { ApiProperty, ApiSchema } from '@nestjs/swagger';
@ApiSchema({
name: 'File',
})
export class FileVo {
@ApiProperty()
url: string;
}