skip to Main Content

import { Controller, Post, UploadedFile, Get, Param, Res, UseInterceptors, StreamableFile, Header } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Response } from 'express';
import { createReadStream } from 'fs';
import { join } from 'path';

@Controller()
export class FileController {

    @Get('file/:fileName')
    @Header('Content-Type', 'application/json')
    downloadFile(@Res({ passthrough: true }) res: Response, @Param('fileName') fileName): StreamableFile {
        const file = createReadStream(join(process.cwd(), fileName));
        res.set({
            'Content-Disposition': 'attachment; filename=' + fileName
        });
        return new StreamableFile(file);
    }


    @Get('video/:fileName')
    viewVideo(@Res() res: Response, @Param('fileName') fileName: string): string {
        const videoPath = join(process.cwd(), fileName)
        return fileName;
    }

    @Post('upload')
    @UseInterceptors(FileInterceptor('file'))
    uploadFile(@UploadedFile() file: Express.Multer.File) {
        console.log(file.filename);
        console.log(file.path);
        return file.filename;
    }

}

Here is my nest js code

below are required logs

[Nest] 28008 – 04/18/2024, 1:51:21 PM LOG [RoutesResolver] FileController {/file}: +0ms
[Nest] 28008 – 04/18/2024, 1:51:21 PM LOG [RouterExplorer] Mapped {/file/:fileName, GET} route +1ms
[Nest] 28008 – 04/18/2024, 1:51:21 PM LOG [RouterExplorer] Mapped {/file/upload, POST} route +0ms

my route for video/:fileName is not getting mapped.

How to solve ?
i have restarted application several times.

I restarted application several times, tried different routes as well, tried chat gpt but could not solve.

2

Answers


  1. It is because you are using @Res() res: Response in the method parameters, in that case NEST expects you to handle response data which includes setting headers, status code, and sending the response.

    Remove @Res() res: Response and the endpoint should map.

    Login or Signup to reply.
  2. Looks like you’re missing the route path for your controller. Try adding a route prefix to the @Controller() decorator, like @Controller('files'). This way, your routes will be files/file/:fileName and files/video/:fileName. Also, ensure your @Post('upload') interceptor has the right syntax. The code snippet seems cut off.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search