File size: 1,509 Bytes
d988ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { Controller, Get, Param, Res, Req, NotFoundException } from '@nestjs/common';
import { Request, Response } from 'express';
import { FilesystemService } from './filesystem.service';
import * as path from 'path';
import * as mime from 'mime-types';

@Controller('files')
export class FilesystemController {
  constructor(private readonly filesystemService: FilesystemService) {}

  @Get(':roomCode/:fileName')
  async serveFile(
    @Param('roomCode') roomCode: string,
    @Param('fileName') fileName: string,
    @Req() req: Request,
    @Res() res: Response,
  ) {
    try {
      const fileBuffer = await this.filesystemService.getFile(roomCode, fileName);
      
      // Determine content type
      const contentType = mime.lookup(fileName) || 'application/octet-stream';
      
      // Set appropriate headers
      res.setHeader('Content-Type', contentType);
      
      // Get the original filename if provided in the query
      const originalName = req.query.originalName ? decodeURIComponent(req.query.originalName.toString()) : fileName;
      
      // Check if the request has a 'download' query parameter
      const downloadHeader = req.query.download === 'true' 
        ? `attachment; filename="${originalName}"` 
        : `inline; filename="${originalName}"`;
      
      res.setHeader('Content-Disposition', downloadHeader);
      
      // Send the file
      return res.send(fileBuffer);
    } catch (error) {
      throw new NotFoundException('File not found');
    }
  }
}