如何使用nestjs发送blobfile?

mf98qq94  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(471)

我想使用nestjs发送blobfile,这是我第一次使用nodejs。我读了很多文章,但解决不了我的问题。

  1. @Get('/api/font/blob1')
  2. @Header('Content-type', 'font/woff')
  3. async fontBlob1(@Query('text') text, @Query('fontNo') fontNo): Promise<unknown> {
  4. let font = await this.appService.fontBlob(text, fontNo);
  5. console.info('blog')
  6. console.info(font)
  7. return font['data'];
  8. }
  9. async fontBlob(text, fontNo) {
  10. let srcFont = '~/font/official/' + fontNo + '.woff';
  11. let fontmin = new Fontmin()
  12. .src(srcFont)
  13. .use(Fontmin.glyph({
  14. text: text,
  15. hinting: false
  16. })).use(Fontmin.ttf2woff());
  17. const font = await new Promise((resolve, reject) => {
  18. fontmin.run((error, files) => {
  19. if (error) {
  20. reject(error);
  21. }
  22. resolve(files[0].contents);
  23. });
  24. });
  25. console.info('blob service finish')
  26. console.info(font)
  27. return font;
  28. }
wgx48brx

wgx48brx1#

如果您使用nestjs 8,您可以在这里看到文档
否则你可以用装饰器 @Res() 这将为您提供服务器响应的示例。
例子:

  1. @Get('/api/font/blob1')
  2. @Header('Content-type', 'font/woff')
  3. async fontBlob1(
  4. @Query('text') text,
  5. @Query('fontNo') fontNo,
  6. @Res() res,
  7. ): Promise<void> {
  8. let font: Buffer = await this.appService.fontBlob(text, fontNo);
  9. const stream = new Readable();
  10. stream.push(font.buffer);
  11. stream.push(null);
  12. stream.pipe(res);
  13. }

如果您使用fastify nest应用程序,则可以如下操作:

  1. @Get('/api/font/blob1')
  2. @Header('Content-type', 'font/woff')
  3. async fontBlob1(
  4. @Query('text') text,
  5. @Query('fontNo') fontNo,
  6. @Res({ passthrough: true }) res: FastifyReply // <= Type from fastify
  7. ): Promise<void> {
  8. try {
  9. let font: Buffer = await this.appService.fontBlob(text, fontNo);
  10. response.send(file);
  11. } catch (error) {
  12. res.removeHeader('Content-type');
  13. res.removeHeader('Content-disposition');
  14. res.status(error.status).send(error);
  15. }
  16. }
展开查看全部

相关问题