fix: 修复本地上传资源路径解析

This commit is contained in:
Nixevol
2026-07-07 02:23:48 +08:00
parent 98b4b8b079
commit fa98f02458
18 changed files with 186 additions and 48 deletions
+42
View File
@@ -0,0 +1,42 @@
import { mkdtempSync, rmSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { LocalDriver } from './local.driver';
describe('LocalDriver', () => {
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
function createDriver(publicPrefix = '/uploads', cdnBaseUrl = '') {
const localDir = mkdtempSync(join(tmpdir(), 'artveris-storage-'));
tempDirs.push(localDir);
return new LocalDriver({
localDir,
publicPrefix,
cdnBaseUrl,
});
}
it('returns a relative public URL for local uploads without CDN', () => {
expect(createDriver().getPublicUrl('2026/07/file.jpg')).toBe('/uploads/2026/07/file.jpg');
});
it('normalizes trailing slash in public prefix', () => {
expect(createDriver('/uploads/').getPublicUrl('2026/07/file.jpg')).toBe('/uploads/2026/07/file.jpg');
});
it('normalizes missing leading slash in public prefix', () => {
expect(createDriver('uploads').getPublicUrl('2026/07/file.jpg')).toBe('/uploads/2026/07/file.jpg');
});
it('uses CDN base URL when configured', () => {
expect(createDriver('/uploads', 'https://cdn.example.com/assets/').getPublicUrl('2026/07/file.jpg')).toBe(
'https://cdn.example.com/assets/2026/07/file.jpg',
);
});
});
+8 -2
View File
@@ -6,7 +6,6 @@ export interface LocalDriverOptions {
localDir: string;
publicPrefix: string;
cdnBaseUrl: string;
baseUrl: string;
}
// 本地磁盘存储驱动(默认)。文件经 Nest 静态目录对外访问。
@@ -61,10 +60,17 @@ export class LocalDriver implements StorageDriver {
return keys;
}
private getPublicPrefix(): string {
const raw = (this.opts.publicPrefix || '/uploads').trim();
if (raw === '/') return '';
return `/${raw.replace(/^\/+|\/+$/g, '')}`;
}
getPublicUrl(key: string): string {
const publicPath = `${this.getPublicPrefix()}/${key}`;
if (this.opts.cdnBaseUrl) {
return `${this.opts.cdnBaseUrl.replace(/\/$/, '')}/${key}`;
}
return `${this.opts.baseUrl.replace(/\/$/, '')}${this.opts.publicPrefix}/${key}`;
return publicPath;
}
}
@@ -89,7 +89,6 @@ export class StorageAdminService {
localDir: dto.localDir || this.config.get<string>('storage.localDir') || './storage',
publicPrefix: '/uploads',
cdnBaseUrl: dto.cdnBaseUrl || '',
baseUrl: this.config.get<string>('baseUrl') || 'http://localhost:3000',
});
}
-1
View File
@@ -74,7 +74,6 @@ export class StorageService implements OnModuleInit {
localDir: s.localDir,
publicPrefix: s.publicPrefix,
cdnBaseUrl: s.cdnBaseUrl,
baseUrl: this.config.get<string>('baseUrl') || 'http://localhost:3000',
});
this.logger.log('存储驱动:本地磁盘');
return driver;