fix:文件上传功能修复

This commit is contained in:
Jerry 2025-10-11 23:11:48 +08:00
parent 645065b4fb
commit dc479ffbdb
2 changed files with 28 additions and 30 deletions

View File

@ -162,10 +162,13 @@ export class OpenListUtils {
file: fs.ReadStream, file: fs.ReadStream,
): Promise<FileUpload> { ): Promise<FileUpload> {
const url = `${this.apiBaseUrl}/api/fs/put`; const url = `${this.apiBaseUrl}/api/fs/put`;
const stats = fs.statSync(filePath);
const fileSize = stats.size;
const headers = { const headers = {
Authorization: `${token}`, Authorization: `${token}`,
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'Content-Length': file.bytesRead, 'Content-Length': fileSize,
'File-Path': encodeURIComponent(filePathOnServer), 'File-Path': encodeURIComponent(filePathOnServer),
}; };
@ -174,14 +177,17 @@ export class OpenListUtils {
headers, headers,
params: { params: {
path: filePath, path: filePath,
'As-Task': 'true', //作为任务 'As-Task': 'true',
}, },
maxBodyLength: Infinity,
maxContentLength: Infinity,
}); });
this.logger.log(`文件上传成功: ${filePathOnServer}`); this.logger.log(`文件上传成功: ${filePathOnServer}`);
return response.data; return response.data;
} catch (error) { } catch (error) {
this.logger.error('上传文件失败..', error); this.logger.error('上传文件失败..', error);
throw new Error('上传文件失败..'); throw new Error(`上传文件失败: ${error.message || error}`);
} }
} }
} }

View File

@ -186,7 +186,6 @@ export class MemeController {
* @param file * @param file
* @param character * @param character
* @param status * @param status
* @param token
* @param res * @param res
*/ */
@Post('upload') @Post('upload')
@ -210,7 +209,6 @@ export class MemeController {
@UploadedFile() file: Express.Multer.File, @UploadedFile() file: Express.Multer.File,
@Body('character') character: string, @Body('character') character: string,
@Body('status') status: string, @Body('status') status: string,
@Body('token') token: string,
@Res() res: Response, @Res() res: Response,
) { ) {
if (!file) { if (!file) {
@ -218,7 +216,15 @@ export class MemeController {
} }
try { try {
const buffer = file.buffer; const fsp = fs.promises;
const safeCharacter = character?.trim() || 'unknown';
const safeStatus = status?.trim() || 'default';
const memeBasePath = this.pathService.get('meme');
const localDir = path.join(memeBasePath, safeCharacter, safeStatus);
await fsp.mkdir(localDir, { recursive: true });
const buffer = file.buffer || (await fsp.readFile(file.path));
const imgType = await imageType(buffer); const imgType = await imageType(buffer);
if (!imgType || !['jpg', 'png', 'gif', 'webp'].includes(imgType.ext)) { if (!imgType || !['jpg', 'png', 'gif', 'webp'].includes(imgType.ext)) {
throw new HttpException( throw new HttpException(
@ -226,16 +232,10 @@ export class MemeController {
HttpStatus.UNSUPPORTED_MEDIA_TYPE, HttpStatus.UNSUPPORTED_MEDIA_TYPE,
); );
} }
const fsp = fs.promises;
const safeCharacter = character?.trim() || 'unknown';
const safeStatus = status?.trim() || 'default';
const tempDir = path.join(this.pathService.get('temp'), 'meme');
await fsp.mkdir(tempDir, { recursive: true });
const remoteMemePath = this.configService.get('OPENLIST_API_MEME_PATH'); const remoteMemePath = this.configService.get('OPENLIST_API_MEME_PATH');
const remoteDir = `${remoteMemePath}/${safeCharacter}/${safeStatus}/`; const remoteDir = `${remoteMemePath}/${safeCharacter}/${safeStatus}/`;
let fileList: string[] = []; let fileList: string[] = [];
try { try {
const listResult = await this.openListService.listFiles(remoteDir); const listResult = await this.openListService.listFiles(remoteDir);
if ( if (
@ -259,26 +259,18 @@ export class MemeController {
const nextNumber = const nextNumber =
usedNumbers.length > 0 ? Math.max(...usedNumbers) + 1 : 1; usedNumbers.length > 0 ? Math.max(...usedNumbers) + 1 : 1;
const filename = `${nextNumber}.${imgType.ext}`; const remoteFilename = `${nextNumber}.${imgType.ext}`;
const tempFilePath = path.join(tempDir, filename); const remoteFilePath = `${remoteDir}${remoteFilename}`;
await fsp.writeFile(tempFilePath, buffer); const localFilePath = path.join(localDir, remoteFilename);
//const openlistBasePath = this.configService.get('OPENLIST_API_BASE_PATH'); await fsp.writeFile(localFilePath, buffer);
const fileStream = fs.createReadStream(localFilePath);
const openListTargetPath = `${remoteDir}${filename}`;
const fileStream = fs.createReadStream(tempFilePath);
await this.openListService.uploadFile( await this.openListService.uploadFile(
tempFilePath, localFilePath,
fileStream, fileStream,
openListTargetPath, remoteFilePath,
); );
this.logger.log(`表情包上传成功: ${remoteFilePath}`);
await fsp.unlink(tempFilePath); return '表情上传成功!';
this.logger.log(`表情包上传成功: ${openListTargetPath}`);
return res.status(200).json({
message: '表情上传成功!',
path: openListTargetPath,
filename,
});
} catch (error) { } catch (error) {
this.logger.error('表情包上传失败:', error); this.logger.error('表情包上传失败:', error);
throw new HttpException( throw new HttpException(