Nestjs 图片上传(一)

1、安装依赖

npm install multer
npm install @types/multer --save-dev

2、生成upload模块

nest g res upload

3、配置图片名称及图片存放路径

upload.module.ts

import { Module } from '@nestjs/common';
import { UploadService } from './upload.service';
import { UploadController } from './upload.controller';
import { MulterModule } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { join, extname } from 'path';

@Module({
    imports:[
        MulterModule.register({
            storage: diskStorage({
                // 图片存放路径
                destination: join(__dirname, "../images"),
                // 图片文件名
                filename: (_, file, callback) => {
                    const fileName = `${new Date().getTime() + extname(file.originalname)}`;
                    return callback(null, fileName);
                }
            })
        })
    ],
    controllers: [UploadController],
    providers: [UploadService]
})
export class UploadModule { }

4、上传逻辑实现

upload.controller.ts

import { Controller, Get, Post, Body, Patch, Param, Delete, UseInterceptors, UploadedFile } 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';

@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}`;
    }
}

5、配置访问路径

main.ts

import { VersioningType } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as session from 'express-session';
import { NestExpressApplication } from '@nestjs/platform-express/interfaces';
import { join } from 'path';

async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    app.useStaticAssets(join(__dirname, 'images'),{
        prefix: "/img"
    });
    await app.listen(3000);
}
bootstrap();

6、apifox 上传图片

Nestjs 图片上传(一)_第1张图片

7、上传成功之后访问图片

 7-1、上传文件存放位置

Nestjs 图片上传(一)_第2张图片

7-2、访问上传文件
 

你可能感兴趣的:(typescript)