Nestjs 图片下载

一、download直接下载

1、添加下载代码

uploadController.ts

import { Controller, Get, Post, Body, Patch, Param, Delete, UseInterceptors, UploadedFile, Res } from '@nestjs/common';
import { UploadService } from './upload.service';
import { CreateUploadDto } from './dto/create-upload.dto';
import { UpdateUploadDto } from './dto/update-upload.dto';
import { FileInterceptor } from '@nestjs/platform-express';
import type { Response } from 'express';
import { join } from 'path';

@Controller('upload')
export class UploadController {
    constructor(private readonly uploadService: UploadService) { }
    
    @Post()
    @UseInterceptors(FileInterceptor('file')) // 'file'为前端表单字段名称
    async uploadFile(@UploadedFile() file) {
        console.log('file', file);
        console.log(`${file.originalname} uploaded successfully.`);
        return `Successfully uploaded ${file.originalname}`;
    }
    
    @Get('export')
    downLoad(@Res() res: Response) {
        const url = join(__dirname, '../images/1705545207094.jpg');
        res.download(url);
    }
}

Nestjs 图片下载_第1张图片 

2、apifox调用下载图片接口

 二、使用文件流的方式实现下载

1、uploadControl.ts

import { Controller, Get, Post, Body, Patch, Param, Delete, UseInterceptors, UploadedFile, Res } from '@nestjs/common';
import { UploadService } from './upload.service';
import { CreateUploadDto } from './dto/create-upload.dto';
import { UpdateUploadDto } from './dto/update-upload.dto';
import { FileInterceptor } from '@nestjs/platform-express';
import type { Response } from 'express';
import { zip } from 'compressing';
import { join } from 'path';

@Controller('upload')
export class UploadController {
    constructor(private readonly uploadService: UploadService) { }
    
    @Post()
    @UseInterceptors(FileInterceptor('file')) // 'file'为前端表单字段名称
    async uploadFile(@UploadedFile() file) {
        console.log('file', file);
        console.log(`${file.originalname} uploaded successfully.`);
        return `Successfully uploaded ${file.originalname}`;
    }
    
    @Get('export')
    downLoad(@Res() res: Response) {
        const url = join(__dirname, '../images/1705545207094.jpg');
        res.download(url);
    }
    
    @Get('stream')
    async down(@Res() res:Response) {
        const url = join(__dirname, '../images/1705545207094.jpg');
        const tarStream = new zip.Stream();
        await tarStream.addEntry(url);
        
        res.setHeader('Content-type', 'application/octet-stream');
        
        res.setHeader(
            'Content-Disposition',
            'attachment; filename=test'
        );
        
        tarStream.pipe(res);
    }
}

Nestjs 图片下载_第2张图片

2、web端实现接口调用 





3、效果截图

Nestjs 图片下载_第3张图片

Nestjs 图片下载_第4张图片 

你可能感兴趣的:(状态模式)