为了在NestJS应用程序中实现流式文件上传,您可以利用底层HTTP模块(类似于Node.js HTTP服务器示例),同时将其集成到NestJS中。您可以这样做:
设置一个基本的NestJS应用程序
npm i -g @nestjs/cli
nest new file-upload-stream
安装所需依赖项
npm install @nestjs/common @nestjs/core @nestjs/platform-express rxjs
npm install --save-dev @types/node
文件上传控制器
import { Controller, Post, Req, Res } from '@nestjs/common';
import { Request, Response } from 'express';
import { createWriteStream } from 'fs';
import { pipeline } from 'stream';
import { promisify } from 'util';
const pump = promisify(pipeline);
@Controller('upload')
export class UploadController {
@Post()
async uploadFile(@Req() req: Request, @Res() res: Response) {
const filename = req.headers['content-disposition']?.match(/filename="(.+)"/)?.[1];
if (!filename) {
res.status(400).send('Missing filename in Content-Disposition header');
return;
}
const filePath = `./Received-${filename}`;
const fileStream = createWriteStream(filePath);
try {
await pump(req, fileStream);
res.status(200).send('File uploaded successfully');
} catch (err) {
console.error(err);
res.status(500).send('File upload failed');
}
}
}
在模块中注册控制器
import { Module } from '@nestjs/common';
import { UploadController } from './upload.controller';
@Module({
controllers: [UploadController],
})
export class UploadModule {}
然后在应用程序模块中注册它
import { Module } from '@nestjs/common';
import { UploadModule } from './upload/upload.module';
@Module({
imports: [UploadModule],
})
export class AppModule {}
更新main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
客户端脚本
import { createReadStream } from 'node:fs';
async function upload(filename) {
const res = await fetch('http://localhost:3000/upload', {
method: 'POST',
headers: {
'Content-Disposition': `attachment; filename="${filename}"`,
},
duplex: 'half',
body: createReadStream(filename),
});
return res.ok;
}
console.log(await upload('TestVideo.mp4'));
您还可以使用multer中间件,还可以对文件大小和文件类型进行验证