Skip to content

Instantly share code, notes, and snippets.

@fuzunspm
Last active January 15, 2024 22:54
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save fuzunspm/5deac95ac7a552d977339df32bdc202e to your computer and use it in GitHub Desktop.
Save fuzunspm/5deac95ac7a552d977339df32bdc202e to your computer and use it in GitHub Desktop.
Nestjs File download
export default class http {
async download(endpoint) {
const token = this.loadToken();
const invoice = await axios({
url: `${this.NEST_APP_IP}/${endpoint}`,
method: 'GET',
responseType: 'blob',
headers: {
Authorization: `Bearer ${token}`
}}).then((response) => {
return response;
});
}
}
.... in another file ...
const invoicePDF = await http.download(`invoices/download/${rowData[7]}`);
const url = window.URL.createObjectURL(new Blob([invoicePDF.data]));
const link = document.createElement('a');
link.href = url;
document.body.appendChild(link);
link.click();
import { Controller, Post, Body, ValidationPipe, Get, Logger, UseGuards, Param, Header } from '@nestjs/common';
import { InvoicesService } from './invoices.service';
import { User } from '../auth/user.entity';
import { GetUser } from '../auth/get-user.decorator';
import { Invoices } from './invoices.entity';
import { AuthGuard } from '@nestjs/passport';
import * as streamBuffers from 'stream-buffers';
@Controller('invoices')
@UseGuards(AuthGuard())
export class InvoicesController {
constructor(private invoicesService: InvoicesService) { }
@Get('/download/:uuid')
@Header('Content-type', 'application/pdf')
async download(
@Param('uuid') uuid: string,
@GetUser() user: User,
): Promise<Buffer> {
const pdf = await this.invoicesService.download(user, uuid);
return pdf;
}
}
import { Injectable, NotFoundException, Logger } from '@nestjs/common';
import { InvoicesRepository } from '../jobs/invoices.repository';
import { User } from '../auth/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Invoices } from './invoices.entity';
import * as fs from 'fs';
import * as path from 'path';
@Injectable()
export class InvoicesService {
constructor(
@InjectRepository(InvoicesRepository)
private invoicesRepository: InvoicesRepository,
) { }
async download(user: User, uuid: string): Promise<Buffer> {
const found = await this.invoicesRepository.findOne({
where: { invoiceUUID: uuid, invoiceTaxNo: user.taxno },
});
if (!found) {
throw new NotFoundException(`invoice with ${uuid} not found`);
}
const filepath = path.join(__dirname, '..', '..', 'pdf', `${uuid}.pdf`);
const pdf = await new Promise<Buffer>((resolve, reject) => {
fs.readFile(filepath, {}, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
return pdf;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment