Saturday, 16 May 2020

Nest Js Serve Static File , Image and Download Pdf File



import { ControllerGetPostResParamReqHeader } from '@nestjs/common';
import { fsRoot } from './server-config';
import { createReadStream } from 'fs';
import { join } from 'path';
import url = require('url');

@Controller()
export class AppController {

    @Get('/upload/:fileId')
    async serveAvatar(@Param('fileId'fileId, @Res() res): Promise<any> {
        return res.sendFile(fileId, { root: 'upload' });
    }

// serve all nested folder
// @Get('/upload/*')
     // async serveAvatar(@Req() req, @Res() res): Promise<any> {
// const urlObject = url.parse(req.urltrue);
     //    const filePath = decodeURI(urlObject.path).replace('/api/upload/''');
     //    return res.sendFile(filePath , { root: 'upload' });
     // }


    @Get('/test')
    //@Header('Content-Type', 'application/pdf')
    getTest(@Res() response) {
        const url = join(fsRoot(), '/upload/test.pdf');
        const data = createReadStream(url);
        response.setHeader('Content-Type''application/pdf');
        response.setHeader('Content-Disposition''attachment; filename=another.pdf');
        data.pipe(response);
    }
}

// Create upload folder on your project root dir
// If you set app.setGlobalPrefix("api");
// image is serve on http://localhost:3000/api/upload/a.png
// pdf file is serve on http://localhost:3000/api/upload/test.pdf

// **************** server-config.ts Code ****************************

import path = require('path');

export const fsRoot = () => {
     return path.resolve(__dirname'../');
};


No comments:

Post a Comment