NestJS FilesInterceptor上传文件originalname编码异常,求Multer配置方案
NestJS Multer FilesInterceptor 中文/特殊字符文件名编码问题解决
问题描述
使用NestJS的@FilesInterceptor和@UploadedFiles实现文件上传时,带特殊字符的文件名(例如"Tést.pdf")会出现编码错误,获取到的file.originalname变为"teÌst.pdf",期望通过Multer配置直接修复该问题,而非上传后手动转换文件名。
配置层面解决方案
Multer底层依赖busboy处理文件上传,而busboy默认使用latin1编码解析文件名,这和前端通常使用的UTF-8编码不匹配是问题根源。可以通过在FilesInterceptor的配置中添加busboyOptions,指定默认字符集为UTF-8来解决:
@HttpCode(200) @UseInterceptors( FilesInterceptor('files', undefined, { preservePath: true, limits: { fileSize: process.env.FILES_STORAGE_SIZE ? parseInt(process.env.FILES_STORAGE_SIZE) : 1073741824, // 1GB }, // 配置busboy使用utf8编码解析文件名 busboyOptions: { defCharset: 'utf8' } }), ) async uploadFiles( @UploadedFiles() files: Express.Multer.File[], @UserReq('id') userId: number, @Param('parentId') parentId: string | null, )
该配置会让busboy在解析上传文件的原始文件名时直接采用UTF-8编码,从根源上避免编码错误。
备选手动转换方案
如果上述配置因版本兼容性等原因不生效,可继续使用已知的手动转换方法修复编码:
const fileNameEncoded = Buffer.from(file.originalname, 'latin1').toString('utf8');
内容的提问来源于stack exchange,提问作者Kokno
相关产品推荐
相关产品推荐

