oa_based/src/modules/tools/upload/upload.service.ts

60 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-02-28 17:02:46 +08:00
import { MultipartFile } from '@fastify/multipart';
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { isNil } from 'lodash';
import { Repository } from 'typeorm';
2024-02-28 08:32:35 +08:00
2024-02-28 17:02:46 +08:00
import { Storage } from '~/modules/tools/storage/storage.entity';
2024-02-28 08:32:35 +08:00
import {
fileRename,
getExtname,
getFilePath,
getFileType,
getSize,
2024-02-29 09:29:03 +08:00
saveLocalFile
2024-02-28 17:02:46 +08:00
} from '~/utils/file.util';
2024-02-28 08:32:35 +08:00
@Injectable()
export class UploadService {
constructor(
@InjectRepository(Storage)
2024-02-28 17:02:46 +08:00
private storageRepository: Repository<Storage>
2024-02-28 08:32:35 +08:00
) {}
/**
*
*/
async saveFile(
file: MultipartFile,
userId: number,
bussinessModule?: string,
bussinessRecordId?: number
): Promise<{ id: number; path: string }> {
2024-02-28 17:02:46 +08:00
if (isNil(file)) throw new NotFoundException('Have not any file to upload!');
2024-02-28 08:32:35 +08:00
2024-02-28 17:02:46 +08:00
const fileName = file.filename;
const size = getSize(file.file.bytesRead);
const extName = getExtname(fileName);
const type = getFileType(extName);
const name = fileRename(fileName);
const path = getFilePath(name);
2024-02-28 08:32:35 +08:00
2024-02-28 17:02:46 +08:00
saveLocalFile(await file.toBuffer(), name);
2024-02-28 08:32:35 +08:00
2024-03-01 15:23:28 +08:00
const storage = await this.storageRepository.save({
2024-02-28 08:32:35 +08:00
name,
fileName,
extName,
path,
type,
size,
userId,
bussinessModule,
bussinessRecordId
2024-02-28 17:02:46 +08:00
});
2024-02-28 08:32:35 +08:00
2024-03-01 15:23:28 +08:00
return { path, id: storage.id };
2024-02-28 08:32:35 +08:00
}
}